2

I have a folder uploads in the root folder. There is another folder A in the root, and contains a PHP file. I have the following code in the PHP file:

$imgpath = '/uploads/' . $filename;
echo '<img src="' . $imgpath . '" />';
echo (file_exists($imgpath))?'true':'false';

It will show the image, so the file exists, but file_exists shows false.

If I change '/uploads/' to '../uploads/', it will show the image and file_exists shows true. Even if there is no image, file_exists always shows true.

What is the problem?

* Update *

I tried echo dirname(__FILE__);. It shows /....../A, the uploads folder is located at /....../uploads. Moreover, I have another similar PHP file in folder /....../m/A. So I need some kind of universal path. How to get the root path, i.e., /....../?

I also tried $_SERVER['DOCUMENT_ROOT'], but the image cannot be shown, although the path is 100% correct.

3 Answers 3

4

To avoid problems, it's easiest to use an absolute path with file_exists(). The system root / is not the same as your web root (e.g.,) /var/www

Try

# /var/www/A/script.php
$imgpath = '/uploads/' . $filename;

# check in /var/www/uploads/filename
if( file_exists(dirname(__FILE__) . '/..' . $imgpath) ) {
    echo '<img src="' . $imgpath . '" />';
}

EDIT for PHP >= 5.3

$path = "/uploads/${filename}";

if (file_exists(sprinf("%s/..%s", __DIR__, $path)) {
  echo "<img src=\"{$path}\">;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works. But even if there is no such file, file_exists also show true. Why?
3

Starting out with "/" means a relative path on the web, but on file systems that is referencing the folder "uploads" inside the root "/" directory.

Try ./uploads notation or use dirname(__FILE__).

Comments

2

The reason is that your absolute path in HTML is relative to your website root, but in PHP it is relative to the file-system root. They are not the same.

My website root is http://www.example.com/ but my site is developed on the file-system at /var/www/ So if I was in /var/www/index.php and used the path /uploads/, in html that would be http://www.example.com/uploads/ but for a file-system that would be /uploads/. I'm not even in my website directory anymore!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.