zoukankan      html  css  js  c++  java
  • 自己项目中PHP常用工具类大全分享

    Php代码  收藏代码
    1. <?php  
    2.  /** 
    3.  * 助手类 
    4.  * @author www.shouce.ren 
    5.  * 
    6.  */  
    7.  class Helper  
    8.  {  
    9.     /** 
    10.      * 判断当前服务器系统 
    11.      * @return string 
    12.      */  
    13.     public static function getOS(){  
    14.         if(PATH_SEPARATOR == ':'){  
    15.             return 'Linux';  
    16.         }else{  
    17.             return 'Windows';  
    18.         }  
    19.     }  
    20.     /** 
    21.      * 当前微妙数 
    22.      * @return number 
    23.      */  
    24.     public static function microtime_float() {  
    25.         list ( $usec, $sec ) = explode ( " ", microtime () );  
    26.         return (( float ) $usec + ( float ) $sec);  
    27.     }  
    28.     /** 
    29.      * 切割utf-8格式的字符串(一个汉字或者字符占一个字节) 
    30.      * 
    31.      * @author zhao jinhan 
    32.      * @version v1.0.0 
    33.      * 
    34.      */  
    35.     public static function truncate_utf8_string($string, $length, $etc = '...') {  
    36.         $result = '';  
    37.         $string = html_entity_decode ( trim ( strip_tags ( $string ) ), ENT_QUOTES, 'UTF-8' );  
    38.         $strlen = strlen ( $string );  
    39.         for($i = 0; (($i < $strlen) && ($length > 0)); $i ++) {  
    40.             if ($number = strpos ( str_pad ( decbin ( ord ( substr ( $string, $i, 1 ) ) ), 8, '0', STR_PAD_LEFT ), '0' )) {  
    41.                 if ($length < 1.0) {  
    42.                     break;  
    43.                 }  
    44.                 $result .= substr ( $string, $i, $number );  
    45.                 $length -= 1.0;  
    46.                 $i += $number - 1;  
    47.             } else {  
    48.                 $result .= substr ( $string, $i, 1 );  
    49.                 $length -= 0.5;  
    50.             }  
    51.         }  
    52.         $result = htmlspecialchars ( $result, ENT_QUOTES, 'UTF-8' );  
    53.         if ($i < $strlen) {  
    54.             $result .= $etc;  
    55.         }  
    56.         return $result;  
    57.     }  
    58.     /** 
    59.      * 遍历文件夹 
    60.      * @param string $dir 
    61.      * @param boolean $all  true表示递归遍历 
    62.      * @return array 
    63.      */  
    64.     public static function scanfDir($dir='', $all = false, &$ret = array()){  
    65.         if ( false !== ($handle = opendir ( $dir ))) {  
    66.             while ( false !== ($file = readdir ( $handle )) ) {  
    67.                 if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) {  
    68.                     $cur_path = $dir . '/' . $file;  
    69.                     if (is_dir ( $cur_path )) {  
    70.                         $ret['dirs'][] =$cur_path;  
    71.                         $all && self::scanfDir( $cur_path, $all, $ret);  
    72.                     } else {  
    73.                         $ret ['files'] [] = $cur_path;  
    74.                     }  
    75.                 }  
    76.             }  
    77.             closedir ( $handle );  
    78.         }  
    79.         return $ret;  
    80.     }  
    81.     /** 
    82.      * 邮件发送 
    83.      * @param string $toemail 
    84.      * @param string $subject 
    85.      * @param string $message 
    86.      * @return boolean 
    87.      */  
    88.     public static function sendMail($toemail = '', $subject = '', $message = '') {  
    89.         $mailer = Yii::createComponent ( 'application.extensions.mailer.EMailer' );  
    90.         //邮件配置  
    91.         $mailer->SetLanguage('zh_cn');  
    92.         $mailer->Host = Yii::app()->params['emailHost']; //发送邮件服务器  
    93.         $mailer->Port = Yii::app()->params['emailPort']; //邮件端口  
    94.         $mailer->Timeout = Yii::app()->params['emailTimeout'];//邮件发送超时时间  
    95.         $mailer->ContentType = 'text/html';//设置html格式  
    96.         $mailer->SMTPAuth = true;  
    97.         $mailer->Username = Yii::app()->params['emailUserName'];  
    98.         $mailer->Password = Yii::app()->params['emailPassword'];  
    99.         $mailer->IsSMTP ();  
    100.         $mailer->From = $mailer->Username; // 发件人邮箱  
    101.         $mailer->FromName = Yii::app()->params['emailFormName']; // 发件人姓名  
    102.         $mailer->AddReplyTo ( $mailer->Username );  
    103.         $mailer->CharSet = 'UTF-8';  
    104.         // 添加邮件日志  
    105.         $modelMail = new MailLog ();  
    106.         $modelMail->accept = $toemail;  
    107.         $modelMail->subject = $subject;  
    108.         $modelMail->message = $message;  
    109.         $modelMail->send_status = 'waiting';  
    110.         $modelMail->save ();  
    111.         // 发送邮件  
    112.         $mailer->AddAddress ( $toemail );  
    113.         $mailer->Subject = $subject;  
    114.         $mailer->Body = $message;  
    115.         if ($mailer->Send () === true) {  
    116.             $modelMail->times = $modelMail->times + 1;  
    117.             $modelMail->send_status = 'success';  
    118.             $modelMail->save ();  
    119.             return true;  
    120.         } else {  
    121.             $error = $mailer->ErrorInfo;  
    122.             $modelMail->times = $modelMail->times + 1;  
    123.             $modelMail->send_status = 'failed';  
    124.             $modelMail->error = $error;  
    125.             $modelMail->save ();  
    126.             return false;  
    127.         }  
    128.     }  
    129.     /** 
    130.      * 判断字符串是utf-8 还是gb2312 
    131.      * @param unknown $str 
    132.      * @param string $default 
    133.      * @return string 
    134.      */  
    135.     public static function utf8_gb2312($str, $default = 'gb2312')  
    136.     {  
    137.         $str = preg_replace("/[x01-x7F]+/", "", $str);  
    138.         if (emptyempty($str)) return $default;  
    139.         $preg =  array(  
    140.             "gb2312" => "/^([xA1-xF7][xA0-xFE])+$/", //正则判断是否是gb2312  
    141.             "utf-8" => "/^[x{4E00}-x{9FA5}]+$/u",      //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了  
    142.         );  
    143.         if ($default == 'gb2312') {  
    144.             $option = 'utf-8';  
    145.         } else {  
    146.             $option = 'gb2312';  
    147.         }  
    148.         if (!preg_match($preg[$default], $str)) {  
    149.             return $option;  
    150.         }  
    151.         $str = @iconv($default, $option, $str);  
    152.         //不能转成 $option, 说明原来的不是 $default  
    153.         if (emptyempty($str)) {  
    154.             return $option;  
    155.         }  
    156.         return $default;  
    157.     }  
    158.     /** 
    159.      * utf-8和gb2312自动转化 
    160.      * @param unknown $string 
    161.      * @param string $outEncoding 
    162.      * @return unknown|string 
    163.      */  
    164.     public static function safeEncoding($string,$outEncoding = 'UTF-8')  
    165.     {  
    166.         $encoding = "UTF-8";  
    167.         for($i = 0; $i < strlen ( $string ); $i ++) {  
    168.             if (ord ( $string {$i} ) < 128)  
    169.                 continue;  
    170.             if ((ord ( $string {$i} ) & 224) == 224) {  
    171.                 // 第一个字节判断通过  
    172.                 $char = $string {++ $i};  
    173.                 if ((ord ( $char ) & 128) == 128) {  
    174.                     // 第二个字节判断通过  
    175.                     $char = $string {++ $i};  
    176.                     if ((ord ( $char ) & 128) == 128) {  
    177.                         $encoding = "UTF-8";  
    178.                         break;  
    179.                     }  
    180.                 }  
    181.             }  
    182.             if ((ord ( $string {$i} ) & 192) == 192) {  
    183.                 // 第一个字节判断通过  
    184.                 $char = $string {++ $i};  
    185.                 if ((ord ( $char ) & 128) == 128) {  
    186.                     // 第二个字节判断通过  
    187.                     $encoding = "GB2312";  
    188.                     break;  
    189.                 }  
    190.             }  
    191.         }  
    192.         if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))  
    193.             return $string;  
    194.         else  
    195.             return @iconv ( $encoding, $outEncoding, $string );  
    196.     }  
    197.     /** 
    198.      * 返回二维数组中某个键名的所有值 
    199.      * @param input $array 
    200.      * @param string $key 
    201.      * @return array 
    202.      */  
    203.     public static function array_key_values($array =array(), $key='')  
    204.     {  
    205.         $ret = array();  
    206.         foreach((array)$array as $k=>$v){  
    207.             $ret[$k] = $v[$key];  
    208.         }  
    209.         return $ret;  
    210.     }  
    211.     /** 
    212.      * 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数) 
    213.      * @param string $file 文件/目录 
    214.      * @return boolean 
    215.      */  
    216.     public static function is_writeable($file) {  
    217.         if (is_dir($file)){  
    218.             $dir = $file;  
    219.             if ($fp = @fopen("$dir/test.txt", 'w')) {  
    220.                 @fclose($fp);  
    221.                 @unlink("$dir/test.txt");  
    222.                 $writeable = 1;  
    223.             } else {  
    224.                 $writeable = 0;  
    225.             }  
    226.         } else {  
    227.             if ($fp = @fopen($file, 'a+')) {  
    228.                 @fclose($fp);  
    229.                 $writeable = 1;  
    230.             } else {  
    231.                 $writeable = 0;  
    232.             }  
    233.         }  
    234.         return $writeable;  
    235.     }  
    236.     /** 
    237.      * 格式化单位 
    238.      */  
    239.     static public function byteFormat( $size, $dec = 2 ) {  
    240.         $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );  
    241.         $pos = 0;  
    242.         while ( $size >= 1024 ) {  
    243.             $size /= 1024;  
    244.             $pos ++;  
    245.         }  
    246.         return round( $size, $dec ) . " " . $a[$pos];  
    247.     }  
    248.     /** 
    249.      * 下拉框,单选按钮 自动选择 
    250.      * 
    251.      * @param $string 输入字符 
    252.      * @param $param  条件 
    253.      * @param $type   类型 
    254.      * selected checked 
    255.      * @return string 
    256.      */  
    257.     static public function selected( $string, $param = 1, $type = 'select' ) {  
    258.         $true = false;  
    259.         if ( is_array( $param ) ) {  
    260.             $true = in_array( $string, $param );  
    261.         }elseif ( $string == $param ) {  
    262.             $true = true;  
    263.         }  
    264.         $return='';  
    265.         if ( $true )  
    266.             $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';  
    267.         echo $return;  
    268.     }  
    269.     /** 
    270.      * 下载远程图片 
    271.      * @param string $url 图片的绝对url 
    272.      * @param string $filepath 文件的完整路径(例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名 
    273.      * @param string $filename 要保存的文件名(不含扩展名) 
    274.      * @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false 
    275.      */  
    276.     static public function downloadImage($url, $filepath, $filename) {  
    277.         //服务器返回的头信息  
    278.         $responseHeaders = array();  
    279.         //原始图片名  
    280.         $originalfilename = '';  
    281.         //图片的后缀名  
    282.         $ext = '';  
    283.         $ch = curl_init($url);  
    284.         //设置curl_exec返回的值包含Http头  
    285.         curl_setopt($ch, CURLOPT_HEADER, 1);  
    286.         //设置curl_exec返回的值包含Http内容  
    287.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    288.         //设置抓取跳转(http 301,302)后的页面  
    289.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
    290.         //设置最多的HTTP重定向的数量  
    291.         curl_setopt($ch, CURLOPT_MAXREDIRS, 3);  
    292.         //服务器返回的数据(包括http头信息和内容)  
    293.         $html = curl_exec($ch);  
    294.         //获取此次抓取的相关信息  
    295.         $httpinfo = curl_getinfo($ch);  
    296.         curl_close($ch);  
    297.         if ($html !== false) {  
    298.             //分离response的header和body,由于服务器可能使用了302跳转,所以此处需要将字符串分离为 2+跳转次数 个子串  
    299.             $httpArr = explode(" ", $html, 2 + $httpinfo['redirect_count']);  
    300.             //倒数第二段是服务器最后一次response的http头  
    301.             $header = $httpArr[count($httpArr) - 2];  
    302.             //倒数第一段是服务器最后一次response的内容  
    303.             $body = $httpArr[count($httpArr) - 1];  
    304.             $header.=" ";  
    305.             //获取最后一次response的header信息  
    306.             preg_match_all('/([a-z0-9-_]+):s*([^ ]+) /i', $header, $matches);  
    307.             if (!emptyempty($matches) && count($matches) == 3 && !emptyempty($matches[1]) && !emptyempty($matches[1])) {  
    308.                 for ($i = 0; $i < count($matches[1]); $i++) {  
    309.                     if (array_key_exists($i, $matches[2])) {  
    310.                         $responseHeaders[$matches[1][$i]] = $matches[2][$i];  
    311.                     }  
    312.                 }  
    313.             }  
    314.             //获取图片后缀名  
    315.             if (0 < preg_match('{(?:[^/\\]+).(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {  
    316.                 $originalfilename = $matches[0];  
    317.                 $ext = $matches[1];  
    318.             } else {  
    319.                 if (array_key_exists('Content-Type', $responseHeaders)) {  
    320.                     if (0 < preg_match('{image/(w+)}i', $responseHeaders['Content-Type'], $extmatches)) {  
    321.                         $ext = $extmatches[1];  
    322.                     }  
    323.                 }  
    324.             }  
    325.             //保存文件  
    326.             if (!emptyempty($ext)) {  
    327.                 //如果目录不存在,则先要创建目录  
    328.                 if(!is_dir($filepath)){  
    329.                     mkdir($filepath, 0777, true);  
    330.                 }  
    331.                 $filepath .= '/'.$filename.".$ext";  
    332.                 $local_file = fopen($filepath, 'w');  
    333.                 if (false !== $local_file) {  
    334.                     if (false !== fwrite($local_file, $body)) {  
    335.                         fclose($local_file);  
    336.                         $sizeinfo = getimagesize($filepath);  
    337.                         return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));  
    338.                     }  
    339.                 }  
    340.             }  
    341.         }  
    342.         return false;  
    343.     }  
    344.     /** 
    345.      * 查找ip是否在某个段位里面 
    346.      * @param string $ip 要查询的ip 
    347.      * @param $arrIP     禁止的ip 
    348.      * @return boolean 
    349.      */  
    350.     public static function ipAccess($ip='0.0.0.0', $arrIP = array()){  
    351.         $access = true;  
    352.         $ip && $arr_cur_ip = explode('.', $ip);  
    353.         foreach((array)$arrIP as $key=> $value){  
    354.             if($value == '*.*.*.*'){  
    355.                 $access = false; //禁止所有  
    356.                 break;  
    357.             }  
    358.             $tmp_arr = explode('.', $value);  
    359.             if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) {  
    360.                 //前两段相同  
    361.                 if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){  
    362.                     //第三段为* 或者相同  
    363.                     if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){  
    364.                         //第四段为* 或者相同  
    365.                         $access = false; //在禁止ip列,则禁止访问  
    366.                         break;  
    367.                     }  
    368.                 }  
    369.             }  
    370.         }  
    371.         return $access;  
    372.     }  
    373.     /** 
    374.      * @param string $string 原文或者密文 
    375.      * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE 
    376.      * @param string $key 密钥 
    377.      * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效 
    378.      * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文 
    379.      * 
    380.      * @example 
    381.      * 
    382.      * $a = authcode('abc', 'ENCODE', 'key'); 
    383.      * $b = authcode($a, 'DECODE', 'key');  // $b(abc) 
    384.      * 
    385.      * $a = authcode('abc', 'ENCODE', 'key', 3600); 
    386.      * $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空 
    387.      */  
    388.     public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {  
    389.         $ckey_length = 4;  
    390.         // 随机密钥长度 取值 0-32;  
    391.         // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。  
    392.         // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方  
    393.         // 当此值为 0 时,则不产生随机密钥  
    394.         $key = md5 ( $key ? $key : 'key' ); //这里可以填写默认key值  
    395.         $keya = md5 ( substr ( $key, 0, 16 ) );  
    396.         $keyb = md5 ( substr ( $key, 16, 16 ) );  
    397.         $keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';  
    398.         $cryptkey = $keya . md5 ( $keya . $keyc );  
    399.         $key_length = strlen ( $cryptkey );  
    400.         $string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;  
    401.         $string_length = strlen ( $string );  
    402.         $result = '';  
    403.         $box = range ( 0, 255 );  
    404.         $rndkey = array ();  
    405.         for($i = 0; $i <= 255; $i ++) {  
    406.             $rndkey [$i] = ord ( $cryptkey [$i % $key_length] );  
    407.         }  
    408.         for($j = $i = 0; $i < 256; $i ++) {  
    409.             $j = ($j + $box [$i] + $rndkey [$i]) % 256;  
    410.             $tmp = $box [$i];  
    411.             $box [$i] = $box [$j];  
    412.             $box [$j] = $tmp;  
    413.         }  
    414.         for($a = $j = $i = 0; $i < $string_length; $i ++) {  
    415.             $a = ($a + 1) % 256;  
    416.             $j = ($j + $box [$a]) % 256;  
    417.             $tmp = $box [$a];  
    418.             $box [$a] = $box [$j];  
    419.             $box [$j] = $tmp;  
    420.             $result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );  
    421.         }  
    422.         if ($operation == 'DECODE') {  
    423.             if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {  
    424.                 return substr ( $result, 26 );  
    425.             } else {  
    426.                 return '';  
    427.             }  
    428.         } else {  
    429.             return $keyc . str_replace ( '=', '', base64_encode ( $result ) );  
    430.         }  
    431.     }  
    432.     public static function gbkToUtf8($str){  
    433.         return iconv("GBK", "UTF-8", $str);  
    434.     }  
    435.     }  

     1000多行代码呢太多了保存发不了,查看并下载完整工具类请到http://www.shouce.ren/post/view/id/1700

     

    QQ技术交流群290551701 http://cxy.liuzhihengseo.com/562.html

  • 相关阅读:
    marquee基本语法和marquee的相关参数设置
    [转]FreeTextBox使用详解
    div+css三级下拉菜单无限制下拉
    让Flash在Firefox和IE下背景透明
    asp.net制作幻灯片
    图片连续滚动代码,左右连续,上下连续不间断滚动
    纯DIV+CSS下拉菜单
    连续滚动图片代码
    sql语句修改access中的字段类型,access数据类型大全!
    非常棒的图片连续滚动代码
  • 原文地址:https://www.cnblogs.com/8hao/p/5412270.html
Copyright © 2011-2022 走看看