我需要检查远程服务器上是否存在特定的文件。用is_file()
和file_exists()
不行。有什么想法如何做到这一点快速和容易吗?
你不需要CURL…检查文件是否存在的开销太大了……
使用PHP的get_header。
$headers=get_headers($url);
然后检查$result[0]是否包含200 OK(这意味着文件在那里)
检查URL是否工作的函数可以是:
function UR_exists($url){
$headers=get_headers($url);
return stripos($headers[0],"200 OK")?true:false;
}
/* You can test a URL like this (sample) */
if(UR_exists("http://www.amazingjokes.com/"))
echo "This page exists";
else
echo "This page does not exist";
你必须使用CURL
function does_url_exists($url) {
$ch = curl_init($url);
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;
}
我刚刚找到了这个解决方案:
if(@getimagesize($remoteImageURL)){
//image exists!
}else{
//image does not exist.
}
来源:http://www.dreamincode.net/forums/topic/11197-checking-if-file-exists-on-remote-server/
嗨,根据我们在2个不同服务器之间的测试,结果如下:
使用curl检查10个.png文件(每个文件大约5mb)平均需要5.7秒。使用header检查同样的事情平均花费7.8秒!
所以在我们的测试中,如果你要检查更大的文件,curl要快得多!
我们的旋度函数是
function remote_file_exists($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if( $httpCode == 200 ){return true;}
return false;
}
这是我们的头部检查示例:
function UR_exists($url){
$headers=get_headers($url);
return stripos($headers[0],"200 OK")?true:false;
}
使用curl执行请求,看看是否返回404状态码。使用HEAD请求方法执行请求,因此它只返回没有正文的头。
您可以使用函数file_get_contents();
if(file_get_contents('https://example.com/example.txt')) {
//File exists
}
$file = 'https://picsum.photos/200/300';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
$headers = get_headers((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER[HTTP_HOST] . '/uploads/' . $MAIN['id'] . '.pdf');
$fileExist = (stripos($headers[0], "200 OK") ? true : false);
if ($fileExist) {
?>
<a class="button" href="/uploads/<?= $MAIN['id'] ?>.pdf" download>скачать</a>
<? }
?>