问题
Here is my code.
$filename = "$myMedia catalog/category/ $myImage.png";
$filename = str_replace(" ", "", $filename);
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
The variable
above outputs http://50.87.6.244/~storeupp/media/catalog/category/Game_Used.png
which does exist. However, it says that it does not exists.
Any idea why?
回答1:
Just try to use like this:
$filename = dirname(__FILE__) . "/ $myMedia catalog/category/ $myImage.png";
$filename = str_replace(" ", "", $filename);
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
回答2:
I don't know, but I think, the following code will be more successful if you have external web items as assets:
$filename = $myMedia."catalog/category/".$myImage.".png";
$headers = @get_headers($filename);
$exists = ($file_headers[0] == 'HTTP/1.1 404 Not Found');
回答3:
OT: Instead of using spaces and str_replace(" ", "", $filename) you can surround variable betwen "{}" brackets.
$filename = "{$myMedia}catalog/category/{$myImage}.png";
回答4:
That file looks like it is outside of your web root. As a result it is not available via the web. If you're trying to check a file that is local on your machine, use the file root instead. (i.e. /path/to/media/catalog/category/Game_Used.png)
回答5:
You need to reference the path to the file or the directory you cannot use http://
links
file_exists documentation
回答6:
In the documentation it states that the file_exists() function is only available with some URL wrappers as of PHP 5.0.
来源:https://stackoverflow.com/questions/15074013/php-if-file-exists