简体   繁体   中英

PHP file_exists directory

I am trying to use file exists in a subdirectory and running into some problems with the directory structure or perhaps something else. This code was working earlier when called from the main directory

The file that includes the command is in a subdirectory that is one directory below the main directory of the domain.

When I call the following on a file that I know exists nothing is returned, neither FALSE nor TRUE

$imgpath1 = 'pics/'.$userid.'_pic.jpg';
$exists = file_exists($imgpath1);
echo "1".$exists;//returns 1

I have tried different variations of the directory such as '/pics...' and also '../pics...' as well as the whole url begininning with ' http://www ....' but cannot get it to return either a FALSE or a TRUE.

Would appreciate any suggestions.

When coercing true to a string, you get a 1 .

When coercing false to a string, you get an empty string.

Here's an example of this:

<?php
echo "True: \"" . true . "\"\n";
echo "False: \"" . false . "\"\n";

echo "True length: " . strlen("" . true) . "\n";
echo "False length: " . strlen("" . false) . "\n"
?>

And the output from running it:

True: "1"
False: ""
True length: 1
False length: 0

So in reality, file_exists($imgpath1) is returning false .

You cannot echo a Boolean as True or False , it will be echoed as 1 or 0 respectively.
Although, you can use the ternary conditional operator , something like :

$exists = file_exists($imgpath1);
echo $exists ? 'true' : 'false';

Try this:

var_dump(realpath(__DIR__.'/../pics'));

If you get false the path doesn't exist, otherwise you get the path as a string.

You could use the following code. It is a little bit verbose.

//get the absolute path /var/www/... 
$currentWorkingDirectory = getcwd(); 

//get the path to the image file
$imgpath1 = $currentWorkingDirectory . '/pics/' . $userid . '_pic.jpg';

//in case the pics folder is one level higher
//$imgpath1 = $currentWorkingDirectory . '/../pics/' . $userid . '_pic.jpg';

//test existence 
if (file_exists($imgpath1)) {
    echo "The file $imgpath1 exists";
} else {
    echo "The file $imgpath1 does not exist";
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM