自己項目中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($filearray('.''..''.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/p_w_picpaths/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("\r\n\r\n"$html, 2 + $httpinfo['redirect_count']);  

  300.             //倒數第二段是服務器最後一次response的http頭  

  301.             $header = $httpArr[count($httpArr) - 2];  

  302.             //倒數第一段是服務器最後一次response的內容  

  303.             $body = $httpArr[count($httpArr) - 1];  

  304.             $header.="\r\n";  

  305.             //獲取最後一次response的header信息  

  306.             preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/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('{p_w_picpath/(\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 = getp_w_picpathsize($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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章