即使文件存在,file_exists()也返回false(远程URL)

时间:2012-05-04 06:49:46

标签: php

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

下面我将介绍准备在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";
}

6 个答案:

答案 0 :(得分:39)

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

答案 1 :(得分:6)

更好的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
}

答案 2 :(得分:5)

  

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

来自http(s) page上的Supported Protocols and Wrappers

Supports stat()   No

答案 3 :(得分: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";

    }

答案 4 :(得分:0)

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;

}

答案 5 :(得分:-1)

您需要的是url_exists之类的内容。请参阅file_exists文档中的评论:http://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;}
    }
?>