我如何检查一个URL是否存在(不是404)在PHP?


当前回答

get_headers()返回一个数组,其中包含服务器响应HTTP请求时发送的报头。

$image_path = 'https://your-domain.com/assets/img/image.jpg';

$file_headers = @get_headers($image_path);
//Prints the response out in an array
//print_r($file_headers); 

if($file_headers[0] == 'HTTP/1.1 404 Not Found'){
   echo 'Failed because path does not exist.</br>';
}else{
   echo 'It works. Your good to go!</br>';
}

其他回答

到目前为止使用get_headers()的最佳和最简单的答案 最好检查字符串“200 ok”。这比检查要好得多

$file_headers = @get_headers($file-path);
$file_headers[0];

因为有时数组键值会变化。所以最好的办法是检查“200 ok”。任何URL都将在get_headers()响应的任何地方有“200 ok”。

function url_exist($url) {
        $urlheaders = get_headers($url);
        //print_r($urlheaders);
        $urlmatches  = preg_grep('/200 ok/i', $urlheaders);
         if(!empty($urlmatches)){
           return true;
         }else{
           return false;
         }
}

现在检查函数是否为真或假

if(url_exist(php-url-variable-here)
  URL exist
}else{
  URL don't exist
}

检查url是在线还是离线——

function get_http_response_code($theURL) {
    $headers = @get_headers($theURL);
    return substr($headers[0], 9, 3);
}

有点老话题了,但是… 我是这样做的:

$file = 'http://www.google.com';
$file_headers = @get_headers($file);
if ($file_headers) {
    $exists = true;
} else {
    $exists = false;
}

get_headers()返回一个数组,其中包含服务器响应HTTP请求时发送的报头。

$image_path = 'https://your-domain.com/assets/img/image.jpg';

$file_headers = @get_headers($image_path);
//Prints the response out in an array
//print_r($file_headers); 

if($file_headers[0] == 'HTTP/1.1 404 Not Found'){
   echo 'Failed because path does not exist.</br>';
}else{
   echo 'It works. Your good to go!</br>';
}
function urlIsOk($url)
{
    $headers = @get_headers($url);
    $httpStatus = intval(substr($headers[0], 9, 3));
    if ($httpStatus<400)
    {
        return true;
    }
    return false;
}