您的位置:首页 > 理论基础 > 计算机网络

PHP获取网址的http code状态码或其它header方法

2016-07-07 13:38 666 查看
之前一直采用curl方案获取http code,代码如下:

$ch = curl_init('http://www.baidu.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);


一直工作的也挺好,今天用这个方法去读取一个200M的url下载链接,结果等了几十秒之后,页面报错了:

Fatal error: Allowed memory size of 134217728 bytes exhausted

去网上搜索了一下,全部是建议调大内存,

再搜索有没有其它方案获取http code,清一色都是上面的代码,没有解决方案,

后面找同事求助,提供了2个解决方案:

方案1:设置 CURLOPT_NOBODY参数为非0值即可,如:

curl_setopt($ch, CURLOPT_NOBODY, 1);

参考:http://php.net/manual/zh/function.curl-setopt.php

方案2:不用curl,直接用php原生的get_headers方法,官方介绍:

http://php.net/manual/zh/function.get-headers.php

代码和执行效果如下(要自己去解析第一行里的200出来):

var_dump(get_headers(‘http://www.baidu.com‘, 1));

array (size=14)
0 => string 'HTTP/1.1 200 OK' (length=15)
'Date' => string 'Thu, 07 Jul 2016 05:35:12 GMT' (length=29)
'Content-Type' => string 'text/html' (length=9)
'Content-Length' => string '14613' (length=5)
'Last-Modified' => string 'Wed, 03 Sep 2014 02:48:32 GMT' (length=29)
'Connection' => string 'Close' (length=5)
'Vary' => string 'Accept-Encoding' (length=15)
'Set-Cookie' =>
array (size=3)
0 => string 'BAIDUID=FD705C2407BC0005A2F813FF457B5A71:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com' (length=129)
1 => string 'BIDUPSID=FD705C2407BC0005A2F813FF457B5A71; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com' (length=125)
2 => string 'PSTM=1467869712; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com' (length=99)
'P3P' => string 'CP=" OTI DSP COR IVA OUR IND COM "' (length=34)
'Server' => string 'BWS/1.1' (length=7)
'X-UA-Compatible' => string 'IE=Edge,chrome=1' (length=16)
'Pragma' => string 'no-cache' (length=8)
'Cache-control' => string 'no-cache' (length=8)
'Accept-Ranges' => string 'bytes' (length=5)


最后,用如下代码,在Windows环境和Centos环境做了一些简单测试n遍后,发现curl方案效率会高一些:

$loop = 100;
$t1 = 0;
$t2 = 0;
$url = 'http://www.baidu.com/';
for ($i = 0; $i < $loop; $i++) {
$time1 = microtime(true);
get_headers($url);
$time2 = microtime(true);
httphelper::getHttpCode($url);
$time3 = microtime(true);
$t1 += $time2 - $time1;
$t2 += $time3 - $time2;
}
var_dump($t1);
var_dump($t2);
die();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php curl memory exhausted