php get_headers超时轮子
2022/06/21    
function get_url_headers($url,$timeout=4)
{
    $user_agent = "Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.3578.98 Safari/537.36";
    $curl = curl_init();                                        //初始化 curl
    curl_setopt($curl, CURLOPT_URL, $url);                      //要访问网页 URL 地址
    curl_setopt($curl, CURLOPT_USERAGENT,$user_agent);         //模拟用户浏览器信息
    curl_setopt($curl, CURLOPT_REFERER,$url) ;               //伪装网页来源 URL
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);                //当Location:重定向时,自动设置header中的Referer:信息
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);             //数据传输的最大允许时间
    curl_setopt($curl, CURLOPT_HEADER, 1);                     //不返回 header 部分
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);            //返回字符串,而非直接输出到屏幕上
    curl_setopt($curl,CURLOPT_NOBODY,true);

    curl_setopt($curl, CURLOPT_FOLLOWLOCATION,1);             //跟踪爬取重定向页面
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, '0');        //不检查 SSL 证书来源
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, '0');        //不检查 证书中 SSL 加密算法是否存在
    curl_setopt($curl, CURLOPT_ENCODING, '');             //解决网页乱码问题
    $data = curl_exec($curl);
    curl_close($curl);
    if($data===false){
        return false;
    }else{
        $dataRst = [];
        $dataArr = preg_split('/\n\r\n/i',$data);
        foreach($dataArr as $key=>$val){
            if(!empty($val)){
                $headerEachArr = preg_split('/\n/',$val);
                $headerJiexiArr = [];
                foreach($headerEachArr as $keyEach=>$valEach){
                    if($keyEach===0){
                        $headerJiexiArr['http_status'] = trim($valEach);
                        preg_match('/ \d+ /',$valEach,$httpStatusCode);
                        if(count($httpStatusCode)){
                            $headerJiexiArr['http_status_code'] = trim($httpStatusCode[0]);
                        }else{
                            $headerJiexiArr['http_status_code']=false;
                        };
                    }else{
                        $headerJiexiArr[preg_split('/: /',$valEach)[0]] = trim(preg_split('/: /',$valEach)[1]);
                    }
                }
                array_push($dataRst,$headerJiexiArr);
            }
        };
        if(count($dataRst)===0){
            return false;
        }else{
            return $dataRst;
        }
    }
}