检查url是否存在php [英] check if url exists php

查看:146
本文介绍了检查url是否存在php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently using the following method to check if a url exists

$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!');
}

这打印未找到!即使访问时页面明显解决了。我打印标题,发现它是因为它返回 302 。有没有办法做一个 strpos 来测试所有可能解决的标头值?

This prints NOT found! even though the page clearly resolves when visited. I print the headers and found it is because it returns a 302. Is there a way of doing a strpos to test for all possible header values that resolve?

标题的当前输出:

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

如果我输入一个我知道失败的网址我得到以下内容:

If I type in a url that i know fails I get the following:

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是否安全?

Is it safe to test simply for a 404?

推荐答案

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

I would use cURL for url verification. An example method would be as follows

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

这篇关于检查url是否存在php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆