我需要检查远程服务器上是否存在特定文件。使用 is_file()
和 file_exists()
无法实现。有没有什么快速简单的方法?
我需要检查远程服务器上是否存在特定文件。使用 is_file()
和 file_exists()
无法实现。有没有什么快速简单的方法?
你不需要CURL来做这件事... 仅仅为了检查文件是否存在而言,这太过繁琐...
$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";
$url
是一个无效的URL,那么它将会导致错误。因此,在函数的开头,您可以使用以下代码来确保它有效:if(filter_var($url, FILTER_VALIDATE_URL) === FALSE)
return false;
- PouriaDiesel你必须使用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;
}
echo is_url_exists('http://stackoverflow.com') ? 'Yes' : 'No';
输出了 Yes
。 - Mayeenul Islam我刚刚找到了这个解决方案:
if(@getimagesize($remoteImageURL)){
//image exists!
}else{
//image does not exist.
}
来源: http://www.dreamincode.net/forums/topic/11197-checking-if-file-exists-on-remote-server/
getimagesize
?就像这里:http://uk1.php.net/getimagesize 如果是的话,文档中说它可以引用本地或远程文件。 - Todd嗨,根据我们在两个不同服务器之间的测试结果如下:
使用curl检查10个.png文件(每个大约5MB)平均需要5.7秒。 使用头文件检查相同内容的时间平均为7.8秒!
因此,在我们的测试中,如果您需要检查更大的文件,则curl要快得多!
我们的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;
}
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>
<? }
?>