获取 http返回值 已贴出php函数,还有更快的方法?

需求:仅需判断 url http返回值,当前采用curl方法,获取页面中的200和302。
还有什么方法比这更快的?

当前采用:

function curl_200($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url); //设置URL
    curl_setopt($curl, CURLOPT_HEADER, 1); //获取Header
    curl_setopt($curl,CURLOPT_NOBODY,true); //Body就不要了吧,我们只是需要Head
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //数据存到成字符串吧,别给我直接输出到屏幕了
    $data = curl_exec($curl); //开始执行啦~
    echo curl_getinfo($curl,CURLINFO_HTTP_CODE); //我知道HTTPSTAT码哦~
    curl_close($curl); //用完记得关掉他
}
阅读 1.8k
3 个回答

HEAD请求就是干这个的

$ curl -I https://www.baidu.com
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Connection: keep-alive
Content-Length: 277
Content-Type: text/html
Date: Thu, 17 Nov 2022 02:20:23 GMT
Etag: "575e1f7c-115"
Last-Modified: Mon, 13 Jun 2016 02:50:36 GMT
Pragma: no-cache
Server: bfe/1.0.8.18

curl中的-I参数就是发起HEAD请求的,你可以加上-v参数看到这个过程

使用内置 get_headers() 函数,需要自己做一下解析

get_headers('https://www.koogua.com', 1);

输出如下:

array(10) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  ["Server"]=>
  string(12) "nginx/1.18.0"
  ["Date"]=>
  string(29) "Thu, 17 Nov 2022 03:17:36 GMT"
  ["Content-Type"]=>
  string(24) "text/html; charset=UTF-8"
  ["Connection"]=>
  string(5) "close"
  ["X-Powered-By"]=>
  string(10) "PHP/7.3.33"
  ["Set-Cookie"]=>
  string(44) "PHPSESSID=h516esldkr9dsui4qjilaakbul; path=/"
  ["Expires"]=>
  string(29) "Thu, 19 Nov 1981 08:52:00 GMT"
  ["Cache-Control"]=>
  string(35) "no-store, no-cache, must-revalidate"
  ["Pragma"]=>
  string(8) "no-cache"
}

从网络资源使用的角度,可以用 fsockopen 函数去做,只读前几个字节,然后关闭连接。

<?php

function get_status_code($host)
{
    $fp = fsockopen($host, 80, $errno, $errstr, 30);
    if ($fp) {
        $out = "GET / HTTP/1.1\r\n";
        $out .= "Host: {$host}\r\n";
        $out .= "Accept-Encoding: gzip, deflate, sdch\r\n";
        $out .= "Accept-Language: en-GB,en-US;q=0.8,en;q=0.6\r\n";
        $out .= "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36\r\n";
        $out .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);
        $tmp = explode(' ', fgets($fp, 13));
        fclose($fp);

        return (int)$tmp[1];
    }

    return 0;
}

var_dump(get_status_code('baidu.com'));

这样是最节约网络资源的方式,对比其他方案,相对要快,一点儿。

但是,如果你想要更快的话,那可以使用 curl_multi_* 系列函数,这个是支持并发的,比其他方案都要快!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题