Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_exists() in PHP and file path

Tags:

php

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.

like image 383
DrXCheng Avatar asked Feb 15 '26 06:02

DrXCheng


1 Answers

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}\">;
}
like image 174
maček Avatar answered Feb 17 '26 20:02

maček



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!