get_headers函数模拟版

作者:matrix 被围观: 3,633 次 发布时间:2014-09-27 分类:零零星星 | 2 条评论 »

这是一个创建于 3471 天前的主题,其中的信息可能已经有所发展或是发生改变。

在sae上发现禁用了get_headers函数,只有另想办法,遂找到php 模拟get_headers函数代码,不过他的这个没有实现302跳转链接的跟踪。

这里自己的代码可以更高度模拟get_headers函数,利用php的curl功能

/*
模拟php的get_headers()函数;
在sae中需要关闭CURLOPT_FOLLOWLOCATION参数,否则不会有Location;缺点是没法跟踪跳转的链接
略有不同:Content-Length: 0 不会显示;一般的处理时没有问题的
*/
function getHeaders($url,$format=0,$FOLLOWLOCATION=1){
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_NOBODY, 1);//不包含网页的内容
    if($FOLLOWLOCATION){
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);//允许链接自动跳转,当系统开启safe_mode或open_basedir,会出错,该关闭
    }
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);//自动referer
    //curl_setopt($curl, CURLOPT_MAXREDIRS, 1);//限定CURLOPT_FOLLOWLOCATION递归返回的数量        
    $header = curl_exec($curl);
    curl_close($curl);
    $back =  array_filter(explode(PHP_EOL,$header));
    //return array_filter(explode(PHP_EOL,$header));
    if($format){
        foreach($back as $val)
        {
            if(preg_match('/^([^:]+): +(.*)$/',$val,$parts))
            {
                if (array_key_exists($parts[1],$v)){
                    $v[$parts[1]] = array_merge_recursive((array)$v[$parts[1]],(array)$parts[2]);
                }
                else
                {
                    $v[$parts[1]]=$parts[2];
                }
            }
            else{
                if(isset($v[0])){
                    $v[]=$val;
                }
                else{
                    $v[0]=$val;
                }
            }
        }
        return $v;
    }
    return $back;
}

说明:
getHeaders()函数的前两个参数和get_headers函数一样;
第三个参数:我在本地测试是没有问题的,只是在sae上测试不同,原因是sae的cul不支持CURLOPT_FOLLOWLOCATION参数,还有很多限制。这就添加个是否开启CURLOPT_FOLLOWLOCATION功能(自动跟踪跳转的链接);
本地测试基本上与get_headers函数相同输出,不影响响应头的获取。

参考:

http://www.phpernote.com/php-function/748.html

http://bbs.php100.com/read-htm-tid-148513.html

其他文章:
本文固定链接:https://www.hhtjim.com/get_headers-function-simulation.html
matrix
本文章由 matrix 于2014年09月27日发布在零零星星分类下,目前没有通告,你可以至底部留下评论。
转载请注明:get_headers函数模拟版-HHTjim'S 部落格
关键字:, , ,

有2 条评论 »

  1. Lostape Lostape 2014-9-28 10:19:04 +0800#1

    最终用来干啥的?

    • Matrix Matrix Moderator 2014-9-30 19:34:16 +0800

      代替get_headers()函数

添加新评论 »

 🙈 😱 😂 😛 😭 😳 😀 😆 👿 😉 😯 😮 😕 😎 😐 😥 😡 😈 💡

插入图片

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!