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 pre
What you need is something like url_exists
. Refer to the comments in the file_exists
docs: http://php.net/manual/en/function.file-exists.php
Here's one of the examples posted:
<?php
function url_exists($url){
$url = str_replace("http://", "", $url);
if (strstr($url, "/")) {
$url = explode("/", $url, 2);
$url[1] = "/".$url[1];
} else {
$url = array($url, "/");
}
$fh = fsockopen($url[0], 80);
if ($fh) {
fputs($fh,"GET ".$url[1]." HTTP/1.1\nHost:".$url[0]."\n\n");
if (fread($fh, 22) == "HTTP/1.1 404 Not Found") { return FALSE; }
else { return TRUE; }
} else { return FALSE;}
}
?>
$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";
}
function check_file ($file){
if ( !preg_match('/\/\//', $file) ) {
if ( file_exists($file) ){
return true;
}
}
else {
$ch = curl_init($file);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == 200){
$status = true;
}else{
$status = false;
}
curl_close($ch);
return $status;
}
return false;
}
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
}
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
From the http(s) page on Supported Protocols and Wrappers:
Supports stat() No
$filename = "http://im.rediff.com/money/2011/jan/19sld3.jpg";
$file_headers = @get_headers($filename);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
//return false;
echo "file not found";
}else {
//return true;
echo "file found";
}