php常用方法整理,方便备用

//curl post请求

function postCurl($url, $data, $time = 120) {

    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
    curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt ( $ch, CURLOPT_TIMEOUT, $time );

    $response = curl_exec ( $ch );
    curl_close ( $ch );

    return $response;
}


//curl get请求

function getCurl($url, $time=120){
    $curl_opt = array(
            CURLOPT_URL => $url,
            CURLOPT_AUTOREFERER => TRUE,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_CONNECTTIMEOUT => 0,
            CURLOPT_TIMEOUT => $time,
    );

    $ch = curl_init();
    curl_setopt_array($ch, $curl_opt);
    $contents = curl_exec($ch);
    curl_close($ch);

    return $contents;
}


//取得IP地址

function get_ip_address()
{
    if( ! empty($_SERVER["HTTP_CLIENT_IP"]))
    {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    else if( ! empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
    {
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    else if( ! empty($_SERVER["REMOTE_ADDR"]))
    {
        $ip = $_SERVER["REMOTE_ADDR"];
    }
    else
    {
        $ip = "";
    }
    return $ip;
}


//过滤参数
function format($string) {
    if(is_array($string)) {
        foreach($string as $key => $value) {
            $string[$key] = format($value);
        }
    }else
    {
        if ( get_magic_quotes_gpc() )
        {
            $string = strip_tags( ( trim( $string ) ) );
        }
        else
        {
            $string = addslashes( strip_tags( ( trim( $string ) ) ) );
        }
        //过滤sql
        $string = preg_replace( '/select( |%20)|delete( |%20)|update( |%20)|insert( |%20)/i', '', $string );
        $string = sacarXss($string);
    }
    return   $string;
}


//过滤XSS攻击
function sacarXss($val) {
    if ( is_array($val) ) {
        $val = array_map( array( $this, 'sacarXss'), $val );
    }
    else {
        $val = preg_replace( '/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val );
        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|\'\\';
        for ( $i = 0; $i < strlen( $search ); $i++ ) {
            $val = preg_replace( '/(&#[x|X]0{0,8}' . dechex( ord( $search[$i] ) ) . ';?)/i', $search[$i], $val ); // with a ;
            $val = preg_replace( '/(�{0,8}' . ord( $search[$i] ) . ';?)/', $search[$i], $val ); // with a ;
        }
        $ra1 = Array( 'javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base' );
        $ra2 = Array( 'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload' );
        $ra = array_merge( $ra1, $ra2 );
        $found = true;
        while ( $found == true ) {
            $val_before = $val;
            for ( $i = 0; $i < sizeof( $ra ); $i++ ) {
                $pattern = '/';
                for ( $j = 0; $j < strlen( $ra[$i] ); $j++ ) {
                    if ( $j > 0 ) {
                        $pattern .= '(';
                        $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
                        $pattern .= '|(�{0,8}([9][10][13]);?)?';
                        $pattern .= ')?';
                    }
                    $pattern .= $ra[$i][$j];
                }
                $pattern .= '/i';
                $replacement = substr( $ra[$i], 0, 2 ) . '' . substr( $ra[$i], 2 );
                $val = preg_replace( $pattern, $replacement, $val );
                if ( $val_before == $val ) {
                    $found = false;
                }else {
                    $val = '';
                    break 2;
                }
            }
        }
    }
    return $val;
}



/**
* 加密解密
* @param string $string 原文或者密文
* @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
* @param string $key 密钥
* @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效
* @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
*
* @example
*
*  $a = authcode('abc', 'ENCODE', 'key');
*  $b = authcode($a, 'DECODE', 'key');  // $b(abc)
*
*  $a = authcode('abc', 'ENCODE', 'key', 3600);
*  $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空
*/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
    $ckey_length = 4;   
    // 随机密钥长度 取值 0-32;
    // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。
    // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方
    // 当此值为 0 时,则不产生随机密钥


    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++)
    {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++)
    {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++)
    {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if($operation == 'DECODE')
    {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
        {
            return substr($result, 26);
        }
        else
        {
            return '';
        }
    }
    else
    {
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}

/**
 * [num_format 数字转化为千分制格式]
 */
function num_format($num){
    if(!is_numeric($num)){
        return false;
    }
    
    $sign = substr($num,0,1);  //符号 正数 负数
    if ($sign != "-") {
        $sign = "";   
    } else {
        $num = substr($num,1);
    }


    $rvalue='';
    $num = explode('.',$num);//把整数和小数分开
    $rl = !isset($num['1']) ? '' : $num['1'];//小数部分的值
    if ($num[0] == 0) {
        $rv = 0;
    } else {
        $j = strlen($num[0]) % 3;//整数有多少位
        $sl = substr($num[0], 0, $j);//前面不满三位的数取出来
        $sr = substr($num[0], $j);//后面的满三位的数取出来
        $i = 0;
        while($i <= strlen($sr)){
        $rvalue = $rvalue.','.substr($sr, $i, 3);//三位三位取出再合并,按逗号隔开
        $i = $i + 3;
        }
        $rvalue = $sl.$rvalue;
        $rvalue = substr($rvalue,0,strlen($rvalue)-1);//去掉最后一个逗号
        $rvalue = explode(',',$rvalue);//分解成数组
        if($rvalue[0]==0){
        array_shift($rvalue);//如果第一个元素为0,删除第一个元素
        }
        $rv = $rvalue[0];//前面不满三位的数
        for($i = 1; $i < count($rvalue); $i++){
        $rv = $rv.','.$rvalue[$i];
        }
    }
    if(!empty($rl)){
    $rvalue = $sign . $rv.'.'.$rl;//小数不为空,整数和小数合并
    }else{
    $rvalue = $sign . $rv;//小数为空,只有整数
    }
    return $rvalue;
}

//创建目录
function makedir($base_path = '') {  
    //判断路径是否存在  
    if (!is_dir ( $base_path )) {  
        mkdir ( $base_path, 0777, TRUE );  
    }
}

/**
 * 获取某月天数
 * $date 日期(年/月)
 */

function get_day( $date )   
{
    $tem = explode('/' , $date);       //切割日期  得到年份和月份
    $year = $tem['0'];
    $month = $tem['1'];
    if( in_array($month , array( 1 , 3 , 5 , 7 , 8 , 01 , 03 , 05 , 07 , 08 , 10 , 12)))
    {
        $text = 31;
    }
    elseif( $month == 2 )
    {
        if ( $year%400 == 0  || ($year%4 == 0 && $year%100 !== 0) )        //判断是否是闰年
        {
            $text = 29;
        }
        else{
            $text = 28;
        }
    }
    else{

        $text = 30;
    }
    return $text;
}

//整数类型时间转化为时间格式
function excelTime($days, $time=false,$str='-'){
    if(!$days)return false;
    if(function_exists("gregoriantojd")){
        if(is_numeric($days)){
            //based on 1900-1-1
            $jd = gregoriantojd(1, 1, 1970);
            $gregorian = jdtogregorian($jd+intval($days)-25569);
            $myDate = explode('/',$gregorian);
            $myDateStr = str_pad($myDate[2],4,'0', STR_PAD_LEFT)
                    .$str.str_pad($myDate[0],2,'0', STR_PAD_LEFT)
                    .$str.str_pad($myDate[1],2,'0', STR_PAD_LEFT)
                    .($time?" 00:00:00":'');
            return $myDateStr;
        }
    }else{
         $date=$days>25568?$days:25569;
         $ofs=(70 * 365 + 17+2) * 86400;
         $days =  date("Y".$str."m".$str."d",($date * 86400) - $ofs).($time ? " 00:00:00" : "");
    }
    return $days;
}
    
/ **
 * 判读是否是日期格式

 * $dateString  :日期 如:2014-11-19
 */
function isDate( $dateString ) {
    return strtotime( date('Y-m-d', strtotime($dateString)) ) === strtotime( $dateString );
}
    
/**
 * 产生随机码
 */
function createCode($len = 6,$srcstr='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz' )
{
    mt_srand();
    $strs="";
    for($i=0;$i<$len;$i++)
    {
        $strs.= $srcstr[mt_rand(0,strlen($srcstr) - 1)];
    }
    return strtoupper($strs);
}

// 生成指定长度的数字随机数
function genCode($len = 5) {
    $rnd = mt_rand(("1" . sprintf("%0" . ($len - 1) . "d", 0)) + 0, ("1" . sprintf("%0" . $len . "d", 0)) - 1);
    $var = sprintf("%0" . $len . "d", $rnd);
    return $var;
}

/**
* 验证手机号是否正确
*/
 function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
 }
 
/**
 * 取得上传文件的后缀
 * @access private
 * @param string $filename 文件名
 * @return boolean
 */
function getExt($filename) {
    $pathinfo = pathinfo($filename);
    return $pathinfo['extension'];
}

/**
 * 二代身份证验证
 * @param string $str 身份证号
 * @return boolean
 */
function _checkIdCard($str) {
    /*
     * S = Sum(Ai*Wi) (2      * Y = Mod(S, 11)
     * C = 对应Y的检验码
     */
    if (! preg_match("/(^\d{15}$)|(^\d{17}([0-9]|[X|x])$)/", $str)) {
        return false;
    }
    if (strlen($str) == 15) {
        return true;
    }
    $checkCode = array(
        '0' => '1',
        '1' => '0',
        '2' => 'X',
        '3' => '9',
        '4' => '8',
        '5' => '7',
        '6' => '6',
        '7' => '5',
        '8' => '4',
        '9' => '3',
        '10' => '2'
    );
    $arr = str_split($str); // 分割字符串
    $arr = array_reverse($arr); // 反正数组
    $code = $arr[0]; // 获取校验码
    if ($code == 'x') {
        $code = 'X';
    }
    unset($arr[0]);
    /* 计算校验码 */
    $i = 2;
    foreach ($arr as $value) {
        $Ai = $value;
        $Wi = pow(2, $i - 1) % 11;
        $S += $Ai * $Wi;
        ++ $i;
    }
    $Y = $S % 11;
    $C = $checkCode[$Y];
    
    if ($C == $code) {
        return true;
    } else {
        return false;
    }
}





3.将xml格式转换为数组

$xml = (array)simplexml_load_string($xmldata); //simplexml_load_string是将xml转换为对象,用(array)再强制转换成数组,但只能强制转换最外围的


4.php转换编码格式

$xmldata = iconv("UTF-8","GBK",$xmldata); //将utf8转换为GBK

 iconv('GB2312', 'UTF-8', $str); //将字符串的编码从GB2312转到UTF-8 

print_r(iconv_get_encoding()); //得到当前页面编码信息 
echo iconv_strlen($str, 'UTF-8'); //得到设定编码的字符串长度 


5、加 ”p3p“头:解决部分浏览器cookie跨域的问题

header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');




你可能感兴趣的:(php)