如何从 URL 检查文件是否存在

2022-08-30 09:32:23

我需要检查远程服务器上是否存在特定文件。使用 和 不起作用。任何想法如何快速轻松地做到这一点?is_file()file_exists()


答案 1

你不需要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";

答案 2

你必须使用卷曲

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;
}

推荐