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

Szy*_*oda 15 php

file_exists()即使提供的图像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";
}
Run Code Online (Sandbox Code Playgroud)

Gil*_*ong 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";
}
Run Code Online (Sandbox Code Playgroud)

  • k我不得不从`if($ file_headers [0] =='HTTP/1.0 404 Not Found')更改标题{`到`if($ file_headers [0] =='HTTP/1.1 404 Not Found'){`谢谢,你真的帮到了我. (5认同)

Mau*_*chi 7

一个更好的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
}
Run Code Online (Sandbox Code Playgroud)


Amb*_*ber 5

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

HTTP(S)页面支持的协议和包装:

Supports stat()   No
Run Code Online (Sandbox Code Playgroud)