常用函数收集——持续更新

2017-05-24  本文已影响33人  廷裕同学
/*
 * 
 * 生成验证字符串
 */
private function createNonceStr($length = 16)
{
     $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
 }

/*
 * 
 * 拼接签名字符串
 * @param array $urlObj
 * 
 * @return 返回已经拼接好的字符串
 */
private function ToUrlParams($urlObj)
{
    $buff = "";
    foreach ($urlObj as $k => $v)
    {
        if($k != "sign"){
            $buff .= $k . "=" . $v . "&";
        }
    }
    
    $buff = trim($buff, "&");
    return $buff;
}

 /*
 * 获取中文字首字母信息
 */
function getfirstchar($s0)
{
    $firstchar_ord = ord(strtoupper($s0{0}));
    if (($firstchar_ord>=65 and $firstchar_ord<=91)or($firstchar_ord>=48 and $firstchar_ord<=57)) return strtoupper($s0{0});
    $s=iconv("UTF-8","gb2312", $s0);
    $asc=ord($s{0})*256+ord($s{1})-65536;
    if($asc>=-20319 and $asc<=-20284)return "A";
    if($asc>=-20283 and $asc<=-19776)return "B";
    if($asc>=-19775 and $asc<=-19219)return "C";
     if($asc>=-19218 and $asc<=-18711)return "D";
    if($asc>=-18710 and $asc<=-18527)return "E";
    if($asc>=-18526 and $asc<=-18240)return "F";
    if($asc>=-18239 and $asc<=-17923)return "G";
    if($asc>=-17922 and $asc<=-17418)return "H";
    if($asc>=-17417 and $asc<=-16475)return "J";
    if($asc>=-16474 and $asc<=-16213)return "K";
    if($asc>=-16212 and $asc<=-15641)return "L";
    if($asc>=-15640 and $asc<=-15166)return "M";
    if($asc>=-15165 and $asc<=-14923)return "N";
    if($asc>=-14922 and $asc<=-14915)return "O";
    if($asc>=-14914 and $asc<=-14631)return "P";
    if($asc>=-14630 and $asc<=-14150)return "Q";
    if($asc>=-14149 and $asc<=-14091)return "R";
    if($asc>=-14090 and $asc<=-13319)return "S";
    if($asc>=-13318 and $asc<=-12839)return "T";
    if($asc>=-12838 and $asc<=-12557)return "W";
    if($asc>=-12556 and $asc<=-11848)return "X";
    if($asc>=-11847 and $asc<=-11056)return "Y";
    if($asc>=-11055 and $asc<=-10247)return "Z";
    return null;
}
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
/**
 * 字符串加密、解密函数
 *
 *
 * @param   string  $txt        字符串
 * @param   string  $operation  ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
 * @param   string  $key        密钥:数字、字母、下划线
 * @param   string  $expiry     过期时间
 * @return  string
 */
function encry_code($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
        $ckey_length = 4;
        $key = md5($key != '' ? $key : config('encry_key'));
        $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(strtr(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 . rtrim(strtr(base64_encode($result), '+/', '-_'), '=');
        }
    }
/*
 * 函数说明:截取指定长度的字符串
 *         utf-8专用 汉字和大写字母长度算1,其它字符长度算0.5
 *
 * @param  string  $str  原字符串
 * @param  int     $len  截取长度
 * @param  string  $etc  省略字符...
 * @return string        截取后的字符串
 */
  function ReStrLen($str, $len=10, $etc='...')
  {
        $restr = '';
        $i = 0;
        $n = 0.0;

        //字符串的字节数
        $strlen = strlen($str);
        while(($n < $len) and ($i < $strlen))
        {
           $temp_str = substr($str, $i, 1);

           //得到字符串中第$i位字符的ASCII码
           $ascnum = ord($temp_str);

           //如果ASCII位高与252
           if($ascnum >= 252) 
           {
                //根据UTF-8编码规范,将6个连续的字符计为单个字符
                $restr = $restr.substr($str, $i, 6); 
                //实际Byte计为6
                $i = $i + 6; 
                //字串长度计1
                  $n++; 
       }
       else if($ascnum >= 248)
       {
            $restr = $restr.substr($str, $i, 5);
            $i = $i + 5;
            $n++;
       }
       else if($ascnum >= 240)
       {
            $restr = $restr.substr($str, $i, 4);
            $i = $i + 4;
            $n++;
       }
       else if($ascnum >= 224)
       {
            $restr = $restr.substr($str, $i, 3);
            $i = $i + 3 ;
            $n++;
       }
       else if ($ascnum >= 192)
       {
            $restr = $restr.substr($str, $i, 2);
            $i = $i + 2;
            $n++;
       }

       //如果是大写字母 I除外
       else if($ascnum>=65 and $ascnum<=90 and $ascnum!=73)
       {
            $restr = $restr.substr($str, $i, 1);
            //实际的Byte数仍计1个
            $i = $i + 1; 
            //但考虑整体美观,大写字母计成一个高位字符
            $n++; 
       }

       //%,&,@,m,w 字符按1个字符宽
       else if(!(array_search($ascnum, array(37, 38, 64, 109 ,119)) === FALSE))
       {
            $restr = $restr.substr($str, $i, 1);
            //实际的Byte数仍计1个
            $i = $i + 1;
            //但考虑整体美观,这些字条计成一个高位字符
            $n++; 
       }

       //其他情况下,包括小写字母和半角标点符号
       else
       {
            $restr = $restr.substr($str, $i, 1);
            //实际的Byte数计1个
            $i = $i + 1; 
            //其余的小写字母和半角标点等与半个高位字符宽
            $n = $n + 0.5; 
       }
    }

    //超过长度时在尾处加上省略号
    if($i < $strlen)
    {
       $restr = $restr.$etc;
    }

    return $restr;

}

/*
 * 获得当前的页面文件的url
 */
public function GetCurUrl()
{
    if(!empty($_SERVER['REQUEST_URI']))
    {
        $nowurls = explode('?',$_SERVER['REQUEST_URI']);
        $nowurl = $nowurls[0];
    }
    else
    {
        $nowurl = $_SERVER['PHP_SELF'];
    }

    return $nowurl;
}
//查看数据大小
function GetRealSize($size)
{
    $kb = 1024;          // Kilobyte
    $mb = 1024 * $kb;    // Megabyte
    $gb = 1024 * $mb;    // Gigabyte
    $tb = 1024 * $gb;    // Terabyte

    if($size < $kb)
        return $size.'B';

    else if($size < $mb)
        return round($size/$kb,2).'KB';

    else if($size < $gb)
        return round($size/$mb,2).'MB';

    else if($size < $tb)
        return round($size/$gb,2).'GB';

    else
        return round($size/$tb,2).'TB';
}
//获取文件夹大小
function GetDirSize($dir)
{
    $handle = opendir($dir);
    $fsize  = '';

    while(($fname = readdir($handle)) !== false)
    {
        if($fname != '.' && $fname != '..')
        {
            if(is_dir("$dir/$fname"))
                $fsize += GetDirSize("$dir/$fname");
            else
                $fsize += filesize("$dir/$fname");
        }
    }

    closedir($handle);
    if(empty($fsize)) $fsize = 0;

    return $fsize;
}
//创建多级目录
function MkDirs($dir)
{ 
    return is_dir($dir) or (MkDirs(dirname($dir)) and mkdir($dir, 0777)); 
}
//读取文件内容
function Readf($file)
{
    if(file_exists($file) && is_readable($file))
    {
        if(function_exists('file_get_contents'))
        {
            $str = file_get_contents($file);
        }
        else
        {
            $str = '';

            $fp = fopen($file, 'r');
            while(!feof($fp))
            {
                $str .= fgets($fp, 1024);
            }
            fclose($fp);
        }
        return $str;
    }
    else
    {
        return FALSE;
    }
}
// 写入文件内容
function Writef($file,$str,$mode='w')
{
    if(file_exists($file) && is_writable($file))
    {
        $fp = fopen($file, $mode);
        flock($fp, 3);
        fwrite($fp, $str);
        fclose($fp);

        return TRUE;
    }
    else if(!file_exists($file))
    {
        $fp = fopen($file, $mode);
        flock($fp, 3);
        fwrite($fp, $str);
        fclose($fp);
    }
    else
    {
        return FALSE;
    }
}
// 清除HTML
function ClearHtml($str)
{
    $str = strip_tags($str);

    //首先去掉头尾空格
    $str = trim($str);

    //接着去掉两个空格以上的
    $str = preg_replace('/\s(?=\s)/', '', $str);

    //最后将非空格替换为一个空格
    $str = preg_replace('/[\n\r\t]/', ' ', $str);

    return $str;
}
// 是否移动设备访问
function IsMobile()
{

    //如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if(isset($_SERVER['HTTP_X_WAP_PROFILE']))  return TRUE;

    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if(isset($_SERVER['HTTP_VIA']))
    {
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }

    //判断手机发送的客户端标志,兼容性有待提高
    if(isset($_SERVER['HTTP_USER_AGENT']))
    {

        $clientkeywords = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');

        //从HTTP_USER_AGENT中查找手机浏览器的关键字
        if(preg_match('/('.implode('|', $clientkeywords).')/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return TRUE;
        }
    }

    //协议法,因为有可能不准确,放到最后判断
    if(isset($_SERVER['HTTP_ACCEPT']))
    {
        //如果只支持wml并且不支持html那一定是移动设备
        //如果支持wml和html但是wml在html之前则是移动设备
        if((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) &&
           (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false ||
           (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
                return TRUE;
        }
    }

    return FALSE;
}
上一篇下一篇

猜你喜欢

热点阅读