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, ie, /....../
?
I also tried $_SERVER['DOCUMENT_ROOT']
, but the image cannot be shown, although the path is 100% correct.
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 (eg,) /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}\">;
}
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__)
.
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.