PHP使用file_get_contents()检查外部服务器上是否存在文件

Checking file exists on external server using file_get_contents() method, does this method will work properly?

$url_file = "http://website.com/dir/filename.php";
$contents = file_get_contents($url_file);

if($contents){
echo "File Exists!";
} else {
echo "File Doesn't Exists!";
}

I think best method for me is using this script:

$file = "http://website.com/dir/filename.php";
$file_headers = get_headers($file);

If file not exists output for $file_headers[0] is: HTTP/1.0 404 Not Found or HTTP/1.1 404 Not Found

Use strpos method to check 404 string if file doesn't exists:

if(strpos($file_headers[0], '404') !== false){
echo "File Doesn't Exists!";
} else {
echo "File Exists!";
}

Thanks for all help :)

This would work for what you are looking to do. As seen here http://php.net/manual/en/function.file-exists.php#75064

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

Both answers from blamonet and Ajie Kurniyawan are somewhat correct but there are more failures than 404(3xx, 4xx, 5xx responses). There are a lot of HTTP responses that would fail to "get/download" a file from a given server.

So I would suggest to check if 200 OK response.

$file = "http://website.com/dir/filename.php";
$file_headers = @get_headers($file);

if ($file_headers) {
  if (strpos($file_headers[0], ' 200 OK') === true) {
    echo "File Exists";
  } else {
    echo "File Doesn't Exist, Access Denied, URL Moved etc";
    //you can check more responses here 404, 403, 301, 302 etc 
  }
} else {
  echo "Server has not responded. No headers or file to show.";
}