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

之前一直采用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();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

游北亮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值