get_headers函数模拟版

作者:matrix 发布时间:2014 年 9 月 27 日 分类:零零星星

在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

Python版PHP内置的MD5()函数

作者:matrix 发布时间:2014 年 9 月 1 日 分类:Python

初玩Python很不习惯那个md5函数。还好有人分享了相关代码,非常感谢。

import hashlib
def md5 (s, raw_output = False):
    res = hashlib.md5 (s)
    if raw_output:
        return res.digest ()
    return res.hexdigest ()

如果是Python2.5 :

# Python 2.5+
import hashlib
hashlib.md5("welcome").hexdigest()
# pre-2.5, removed in Python 3
import md5
md5.md5("welcome").hexdigest()

参考:Python 实现PHP内置MD5函数方法