问题
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.
回答1:
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
.
回答2:
Try this:
var_dump(realpath(__DIR__.'/../pics'));
If you get false the path doesn't exist, otherwise you get the path as a string.
回答3:
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';
回答4:
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";
}
来源:https://stackoverflow.com/questions/33311030/php-file-exists-directory