20

file_exists()即使提供要检查的图像存在,我也会返回 false https://www.google.pl/logos/2012/haring-12-hp.png。为什么?

下面我将展示准备在 localhost 上触发的完整失败的 PHP 代码:

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

6 回答 6

44
$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";
}
于 2012-05-04T06:56:31.717 回答
8

更好的 if 语句,不查看 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
}
于 2014-07-09T12:42:45.210 回答
6

从 PHP 5.0.0 开始,这个函数也可以与一些 URL 包装器一起使用。请参阅支持的协议和包装器以确定哪些包装器支持 stat() 系列功能。

Supported Protocols and Wrappers上的http(s) 页面

Supports stat()   No
于 2012-05-04T06:52:32.907 回答
1
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;

}
于 2017-10-06T10:36:31.973 回答
0
    $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";

    }
于 2015-04-01T10:29:19.843 回答
-1

你需要的是类似url_exists. 请参阅文档中的注释:http file_exists: //php.net/manual/en/function.file-exists.php

这是发布的示例之一:

<?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;}
    }
?>
于 2012-05-04T06:54:51.487 回答