检查url是否存在php


check if url exists php

我目前正在使用以下方法来检查url是否存在

$url = 'https://www.facebook.com/a-test-example-232397848665383511';
$headers = @get_headers($url);
if(strpos($headers[0],'200')===false){
    print('NOT found!');
} else {
    print('found!');
}

这将打印NOT found!,即使页面在访问时已清晰解析。我打印了标题,发现这是因为它返回了一个302。是否有一种方法可以执行strpos来测试所有可能解析的标头值?

收割台当前输出:

Array
(
    [0] => HTTP/1.1 302 Found
    [1] => Location: https://www.facebook.com/unsupportedbrowser
    [2] => Vary: Accept-Encoding
    [3] => Content-Type: text/html
    // more array items

如果我输入一个我知道失败的url,我会得到以下信息:

Array
(
    [0] => HTTP/1.1 404 Not Found
    [1] => P3P: CP="Facebook does not have a P3P policy." 
    [2] => Strict-Transport-Security: max-age=15552000; preload
    // rest of array

简单测试404是否安全?

我会使用cURL进行url验证。示例方法如下

    public function urlExists($url) {
        $handle = curl_init($url);
        curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
        $response = curl_exec($handle);
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
        curl_close($handle);
        if($httpCode >= 200 && $httpCode <= 400) {
            return true;
        } else {
            return false;
        }
    }

服务器可以使用RFC 2616中描述的不同状态代码进行响应对你来说,所有代码2xx和3xx都意味着成功。

性能说明:get_headers默认使用get方法,但如果您对页面内容不感兴趣,使用HEAD方法会更好、更快。

stream_context_set_default(
  array(
      'http' => array(
          'method' => 'HEAD'
      )
  )
);
$headers = @get_headers($url);
$status = substr($headers[0], 9, 3);
if ($status >= 200 && $status < 400 ) {
  print('found!');
} else {
  print('NOT found!');
}