if =404 php,在PHP中测试404的URL的简便方法?

如果您运行的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}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值