web-dev-qa-db-fra.com

file_exists () renvoie false même si le fichier existe (URL distante)

Ma file_exists() renvoie false même si l'image fournie pour vérifier https://www.google.pl/logos/2012/haring-12-hp.png existe. Pourquoi?

Ci-dessous, je présente un code PHP défaillant prêt à être déclenché sur 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";
}
12
Szymon Toda
$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";
}
36
Gillian Lo Wong

Depuis PHP 5.0.0, cette fonction peut également être utilisée avec certains wrappers d'URL. Reportez-vous à Protocoles et wrappers pris en charge pour déterminer quels wrappers prennent en charge la famille de fonctionnalités stat ().

À partir de la page http (s) on Protocoles pris en charge et wrappers :

Supports stat()   No
5
Amber

Une meilleure déclaration si ne regarde pas la version http

$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
}
5
Maurizio Brioschi
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;

}
    $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";

    }
0
vinod inti