检查该文件是否存在于不同的域而不读取它

Ric*_*nop 2 php

有没有更好的方法来检查文件是否存在(它在不同的域上,因此file_exists不起作用)比这个?

$fp = fsockopen($fileUri, 80, $errno, $errstr, 30);
if (!$fp) {
    // file exists
}
fclose($fp);
Run Code Online (Sandbox Code Playgroud)

Ale*_*tau 11

我喜欢这个.它总是很好用:

$url = "http://www.example.com/index.php";
$header_response = get_headers($url, 1);
if ( strpos( $header_response[0], "404" ) !== false )
{
  // FILE DOES NOT EXIST
}
else
{
  // FILE EXISTS!!
}
Run Code Online (Sandbox Code Playgroud)

  • 我会考虑将第3行更改为`if(strpos($ header_response [0],"200")=== false)`以便403拒绝访问的文件不会返回. (4认同)

Hai*_*vgi 5

看这个例子和解释

$url = "http://www.example.com/index.php";
$header_response = get_headers($url, 1);
if ( strpos( $header_response[0], "404" ) !== false )
{
  // FILE DOES NOT EXIST
} 
else 
{
  // FILE EXISTS!!
}
Run Code Online (Sandbox Code Playgroud)

要么

file_get_contents("http://example.com/path/to/image.gif",0,null,0,1);
Run Code Online (Sandbox Code Playgroud)

将maxlength设置为1