使用file_get_contents()方法检查外部服务器上是否存在文件,此方法是否正常工作?
$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!";
}
我认为对我来说最好的方法是使用这个脚本:
$file = "http://website.com/dir/filename.php";
$file_headers = get_headers($file);
如果文件不存在,$file_headers[0]
的输出为:HTTP/1.0 404 Not Found
或HTTP/1.1 404 Not Found
如果文件不存在,使用strpos方法检查404字符串:
if(strpos($file_headers[0], '404') !== false){
echo "File Doesn't Exists!";
} else {
echo "File Exists!";
}
谢谢大家的帮助
这将适用于您想要做的事情。如下所示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;
}
blamonet和Ajie Kurniyawan的回答都是正确的,但失败的比404(3xx, 4xx, 5xx的回答)要多。有很多HTTP响应无法从给定的服务器"获取/下载"文件。
所以我建议检查200 OK
是否响应。
$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.";
}