My file_exists()
returns false even if provided image to check https://www.google.pl/logos/2012/haring-12-hp.png
exist. Why?
Below I am presenting full failing PHP code ready to fire on localhost:
$filename = 'https://www.google.pl/logos/2012/haring-12-hp.png';
echo "<img src=" . $filename . " />";
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
The file_exists() function in PHP, is used to check if a file or directory exists on the server. But the file_exists() function will not usable if you want to check the file existence on the remote server. The fopen() function is the easiest solution to check if a file URL exists on a remote server using PHP.
exists(): Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise. Files.
The file_exists() function checks whether a file or directory exists.
PHP Create File - fopen() The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
$filename= 'https://www.google.pl/logos/2012/haring-12-hp.png';
$file_headers = @get_headers($filename);
if($file_headers[0] == 'HTTP/1.0 404 Not Found'){
echo "The file $filename does not exist";
} else if ($file_headers[0] == 'HTTP/1.0 302 Found' && $file_headers[7] == 'HTTP/1.0 404 Not Found'){
echo "The file $filename does not exist, and I got redirected to a custom 404 page..";
} else {
echo "The file $filename exists";
}
A better if statement that not looks at http version
$file_headers = @get_headers($remote_filename);
if (stripos($file_headers[0],"404 Not Found") >0 || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0)) {
//throw my exception or do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With