首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP中测试404的URL的简单方法?

在PHP中测试404的URL的简单方法?
EN

Stack Overflow用户
提问于 2009-01-03 00:44:26
回答 14查看 257.8K关注 0票数 161

我自学了一些基本的抓取,我发现有时我输入到我的代码中的URL返回404,这会把我剩下的代码搞得一团糟。

因此,我需要在代码的顶部执行一个测试,以检查URL是否返回404。

这似乎是一项非常简单的任务,但谷歌没有给我任何答案。我担心我在搜索错误的东西。

有一篇博客推荐我这样做:

$valid = @fsockopen($url, 80, $errno, $errstr, 30);

然后测试$valid是否为空。

但是我认为给我带来问题的URL有一个重定向,所以对于所有的值,$valid都是空的。也可能是我做错了什么。

我还研究了"head请求“,但我还没有找到任何可以尝试或尝试的实际代码示例。

有什么建议吗?这是关于卷曲的什么?

EN

回答 14

Stack Overflow用户

回答已采纳

发布于 2009-01-03 00:56:07

如果你使用的是PHP的curl bindings,你可以使用curl_getinfo检查错误代码:

$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);

/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
    /* Handle 404 here. */
}

curl_close($handle);

/* Handle $response here. */
票数 295
EN

Stack Overflow用户

发布于 2009-01-03 01:01:18

如果您运行的是php5,则可以使用:

$url = 'http://www.example.com';
print_r(get_headers($url, 1));

或者,对于php4,用户贡献了以下内容:

/**
This is a modified version of code from "stuart at sixletterwords dot com", at 14-Sep-2005 04:52. This version tries to emulate get_headers() function at PHP4. I think it works fairly well, and is simple. It is not the best emulation available, but it works.

Features:
- supports (and requires) full URLs.
- supports changing of default port in URL.
- stops downloading from socket as soon as end-of-headers is detected.

Limitations:
- only gets the root URL (see line with "GET / HTTP/1.1").
- don't support HTTPS (nor the default HTTPS port).
*/

if(!function_exists('get_headers'))
{
    function get_headers($url,$format=0)
    {
        $url=parse_url($url);
        $end = "\r\n\r\n";
        $fp = fsockopen($url['host'], (empty($url['port'])?80:$url['port']), $errno, $errstr, 30);
        if ($fp)
        {
            $out  = "GET / HTTP/1.1\r\n";
            $out .= "Host: ".$url['host']."\r\n";
            $out .= "Connection: Close\r\n\r\n";
            $var  = '';
            fwrite($fp, $out);
            while (!feof($fp))
            {
                $var.=fgets($fp, 1280);
                if(strpos($var,$end))
                    break;
            }
            fclose($fp);

            $var=preg_replace("/\r\n\r\n.*\$/",'',$var);
            $var=explode("\r\n",$var);
            if($format)
            {
                foreach($var as $i)
                {
                    if(preg_match('/^([a-zA-Z -]+): +(.*)$/',$i,$parts))
                        $v[$parts[1]]=$parts[2];
                }
                return $v;
            }
            else
                return $var;
        }
    }
}

两者的结果都类似于:

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

因此,您只需检查报头响应是否正常,例如:

$headers = get_headers($url, 1);
if ($headers[0] == 'HTTP/1.1 200 OK') {
//valid 
}

if ($headers[0] == 'HTTP/1.1 301 Moved Permanently') {
//moved or redirect page
}

W3C Codes and Definitions

票数 110
EN

Stack Overflow用户

发布于 2011-01-03 21:31:36

使用strager的代码,您还可以检查CURLINFO_HTTP_CODE中的其他代码。一些网站不会报告404,而是简单地重定向到自定义的404页面并返回302 (重定向)或类似的东西。我用这个来检查一个实际的文件(例如,robots.txt)是否存在于服务器上。显然,如果存在这种文件,它不会导致重定向,但如果它不存在,它将重定向到404页面,正如我之前所说的,它可能没有404代码。

function is_404($url) {
    $handle = curl_init($url);
    curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

    /* Get the HTML or whatever is linked in $url. */
    $response = curl_exec($handle);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
    curl_close($handle);

    /* If the document has loaded successfully without any redirection or error */
    if ($httpCode >= 200 && $httpCode < 300) {
        return false;
    } else {
        return true;
    }
}
票数 39
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/408405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档