php implode函数 多维数组

作者:matrix 发布时间:2015 年 3 月 19 日 分类:PHP

PHP implode()[别名join]的作用是将数组元素拼接成一个字符串。
$arr=array('a','b',array('1','2'),'c'); //二维数组
$s=implode(',',$arr);
//返回a,b,Array,c
但是遇到上面这种多维数组这样的implode()就没办法处理。
I was a little worried about the multi-dimensional array implodes listed here, as they are using 'for' loops, which is bad programming practice as arrays are not always nice and neat.

I hope this helps
好在早有解决方案:

<?php  
function multi_implode($glue, $pieces)  
{  
    $string='';  

    if(is_array($pieces))  
    {  
        reset($pieces);  
        while(list($key,$value)=each($pieces))  
        {  
            $string.=$glue.multi_implode($glue, $value);  
        }  
    }  
    else  
    {  
        return $pieces;  
    }  

    return trim($string, $glue);  
}  

说明:和implode()使用参数一样。multi_implode(字符, 数组)
参考:
http://php.chinaunix.net/manual/zh/function.implode.php#94688
http://g.xker.com/97041.html
http://blog.sina.cn/dpool/blog/s/blog_50a1e1740101aet6.html?vt=4

Github项目Mobile-Detect-检测移动设备的php类

作者:matrix 发布时间:2015 年 1 月 14 日 分类:兼容并蓄

Github项目Mobile-Detect-检测移动设备的php类

Mobile-Detect php类可以检测是否为移动设备,不用你自己写代码判断ua。它使用 User-Agent 中的字符串,并结合 HTTP Header,来检测移动设备环境,比较靠谱。

网盘备份:http://pan.baidu.com/s/1pJBMFe7

Github地址:https://github.com/serbanghita/Mobile-Detect
官网:http://mobiledetect.net/
DEMO:http://demo.mobiledetect.net/

函数示例

// 载入并实例化类
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
// 移动设备 (手机和平板).
if ( $detect->isMobile() )
//平板设备
if( $detect->isTablet() )
// 判断os
if( $detect->isiOS() )
if( $detect->isAndroidOS() )
...
// 其他的
$detect->is('Chrome')
$detect->is('iOS')
$detect->is('UC Browser')
...

说明:更多的函数请查看DEMO处

参考:

http://mobiledetect.net/

http://yusi123.com/2607.html

php的file_get_contents函数访问URL显示响应头

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

在用 file_get_contents 访问 http 时,stream wrapper 会把响应头放到当前作用域下的 $http_response_header 数组变量里。

所以说变量$http_response_header就保存了需要的响应头,输出这个变量也就能拿到响应头。

file_get_contents('http://www.hhtjim.com/');
print_r($http_response_header);//输出响应头内容

参考:
http://www.jbxue.com/article/16319.html

PS: 阅读剩余部分 »

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

php的json_decode函数无法解析json

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

phpjson_decode函数用来解析json数据很方便,但是有时候却解析不了。

究其原因找到如下可能性:

1.键名没有用双引号括起来

['name':n,'age',a]
[name:n,age,a]

这两个都不能解析

2.出现多余逗号

['name':n,'age',a,]

###3.有些转义不支持
数据中出现\x26这样的会失败,有时候\'都无法解析。
stripslashes()去掉转义即可!

4.json不支持gbk编码

iconv('GBK', 'UTF-8', $json_data);//使用iconv()函数将GBK转到UTF-8编码

json数据解析前用检测工具测试一下较好:http://www.bejson.com/

150515添加

/* 
 格式化错误的json数据,使其能被json_decode()解析 
 不支持健名有中文、引号、花括号、冒号 
 不支持健指有冒号 
*/  
function format_ErrorJson($data,$quotes_key=false)  
{  
    $con = str_replace('\'','"',$data);//替换单引号为双引号 
    $con = str_replace(array('\\"'),array('<|YH|>'),$con);//替换 
    $con = preg_replace('/(\w+):[ {]?((?<YinHao>"?).*?\k<YinHao>[,}]?)/is', '"$1": $2',$con );//若键名没有双引号则添加  
    if($quotes_key)  
    {  
        $con = preg_replace('/("\w+"): ?([^"\s]+)([,}])[\s]?/is', '$1: "$2"$3',$con );//给键值添加双引号 
    } 
    $con = str_replace(array('<|YH|>'),array('\\"'),$con);//还原替换  
    return $con;  
}  

参考:http://bbs.csdn.net/topics/390496037

http://chenwei.me/p/59.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函数方法

用php的CURL模拟登录正方教务系统

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

学校用的是正方教务系统,这玩意做的太恶心了。

php模拟登录前进行fiddler软件抓包。

每个学校的正方教务系统略有不同,这里仅仅是个样本。

用php的CURL模拟登录正方教务系统

根据抓包结果找到提交所需的post数据

__VIEWSTATE=内容&tbYHM=内容&tbPSW=内容&ddlSF=%D1%A7%C9%FA&imgDL.x=39&imgDL.y=13
说明:第一个内容是登录页面里找到的,第二、三个内容是用户名和密码

判断是否登录成功

成功登录后页面会302跳转到/xsmainfs.aspx?xh=XXX的URL

php代码参考:

<?php
$url = '';//正方教务系统登录地址
$ID = '';
$PA = '';
$cookieid = Get_SessionId($url);//获取登录页面的会话ID
/*
 is_login()函数判断是否登录成功
*/
    function is_login()
    {
        global $url,$ID,$PA,$cookieid;
        preg_match('#value="([^"]+)"#', curl_get($url), $vi);
        $p = '__VIEWSTATE=' . urlencode($vi[1]) . '&tbYHM=' . $ID . '&tbPSW=' . $PA . '&ddlSF=%D1%A7%C9%FA&imgDL.x=39&imgDL.y=13'; //默认学生
        $co = curl_get($url, $p, 0, 0, 0, array('Cookie: ASP.NET_SessionId=' . $cookieid));
        //curl_get('地址/xsleft.aspx?flag=grxx',  array('Cookie: ASP.NET_SessionId=' . $cookieid)); //获取基本信息以前必须访问这个地址
        return strpos($co, "/xsmainfs.aspx?xh=" . $ID)? true : false ;
    }
    function curl_get($url, $add_arry_header = 0)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent: Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_1_2 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7D11 Safari/528.16'));
        if ($add_arry_header)
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $add_arry_header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $get_url = curl_exec($ch);
        curl_close($ch);
        return $get_url;
    }
function Get_SessionId($u) // 获取aspx的会话ID
    {
        $a = get_headers($u);
        $a = str_replace(array(';', ':'), '&', $a[6]);
        parse_str($a, $aa);
        return $aa['ASP_NET_SessionId'] ;
    }
?>

说明:代码不完全可用,只是参考,记录。

ps:

正方教务系统的登录地址还有default4.aspx的精简登录框,模拟这个的话应该更简单。

 

 

PHP的基本规则

作者:matrix 发布时间:2014 年 4 月 23 日 分类:兼容并蓄 零零星星

PHP的基本规则

下面内容来自 php开发实战宝典 附录A: php编码规则

A.1  PHP File文件格式

A.1.1  常规

对于只包含PHP代码的文件,结束标志("?>")是不允许存在的,否则会导致文件末尾被意外地注入空白并显示输出。

由__HALT_COMPILER()允许的任意的二进制代码的内容被Zend Framework PHP文件或由它们产生的文件禁止。这个功能只对特殊的安装脚本开放。

A.1.2  缩进

使用4个空格的缩进,而不使用制表符TAB。
阅读剩余部分 »