检查url是否存在php

0 php http-headers

我目前正在使用以下方法来检查是否存在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!');
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

仅仅测试404是否安全?

Kev*_*nch 8

我会cURL用于网址验证.示例方法如下

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

        if($httpCode >= 200 && $httpCode <= 400) {
            return true;
        } else {
            return false;
        }

        curl_close($handle);
    }
Run Code Online (Sandbox Code Playgroud)

  • 我想你想要$ httpCode <400,而不是$ httpCode <= 400. (3认同)