Home  >  Article  >  Backend Development  >  Share a complete list of commonly used PHP tools in your own projects, share a complete list of PHP tools_PHP Tutorial

Share a complete list of commonly used PHP tools in your own projects, share a complete list of PHP tools_PHP Tutorial

WBOY
WBOYOriginal
2016-07-12 08:54:03841browse

Share a complete list of commonly used PHP tools in your own projects, share a complete list of PHP tools

Php code Share a complete list of commonly used PHP tools in your own projects, share a complete list of PHP tools_PHP Tutorial
  1. /**
  2. * Helper class
  3. * @author www.shouce.ren
  4. *
  5. */
  6. class Helper
  7. {
  8. /**
  9. * Determine the current server system
  10. * @return string
  11. */
  12. public static function getOS(){
  13. if(PATH_SEPARATOR == ':'){
  14.          return 'Linux'; 
  15. }else{
  16. return 'Windows';
  17. }  
  18.  } 
  19. /**
  20. * Current microsecond number
  21. * @return number
  22. */
  23. public static function microtime_float() {
  24. list ( $usec, $sec ) = explode ( " ", microtime () );
  25. return (( float ) $usec ( float ) $sec);
  26. }  
  27.     /**
  28. * Cut a string in utf-8 format (one Chinese character or character occupies one byte)
  29. *
  30. * @author zhao jinhan
  31. * @version v1.0.0
  32. *
  33. */  
  34.     public static function truncate_utf8_string($string, $length, $etc = '...') {  
  35.         $result = '';  
  36.         $string = html_entity_decode ( trim ( strip_tags ( $string ) ), ENT_QUOTES, 'UTF-8' );  
  37.         $strlen = strlen ( $string );  
  38.         for($i = 0; (($i $strlen) && ($length > 0)); $i  ) {  
  39.             if ($number = strpos ( str_pad ( decbin ( ord ( substr ( $string, $i, 1 ) ) ), 8, '0', STR_PAD_LEFT ), '0' )) {  
  40.                 if ($length 
  41.                     break;  
  42.                 }  
  43.                 $result .= substr ( $string, $i, $number );  
  44.                 $length -= 1.0;  
  45.                 $i  = $number - 1;  
  46.             } else {  
  47.                 $result .= substr ( $string, $i, 1 );  
  48.                 $length -= 0.5;  
  49.             }  
  50.         }  
  51.         $result = htmlspecialchars ( $result, ENT_QUOTES, 'UTF-8' );  
  52.         if ($i $strlen) {  
  53.             $result .= $etc;  
  54.         }  
  55.         return $result;  
  56.     }  
  57.     /**
  58. * Traverse folders
  59. * @param string $dir
  60. * @param boolean $all true means recursive traversal
  61. * @return array
  62. */  
  63.     public static function scanfDir($dir='', $all = false, &$ret = array()){  
  64.         if ( false !== ($handle = opendir ( $dir ))) {  
  65.             while ( false !== ($file = readdir ( $handle )) ) {  
  66.                 if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) {  
  67.                     $cur_path = $dir . '/' . $file;  
  68.                     if (is_dir ( $cur_path )) {  
  69.                         $ret['dirs'][] =$cur_path;  
  70.                         $all && self::scanfDir( $cur_path, $all, $ret);  
  71.                     } else {  
  72.                         $ret ['files'] [] = $cur_path;  
  73.                     }  
  74.                 }  
  75.             }  
  76.             closedir ( $handle );  
  77.         }  
  78.         return $ret;  
  79.     }
  80. /** 
  81.      * 邮件发送 
  82.      * @param string $toemail 
  83.      * @param string $subject 
  84.      * @param string $message 
  85.      * @return boolean 
  86.      */
  87. public static function sendMail($toemail = '', $subject = '', $message = '') {
  88. $mailer = Yii::createComponent ( 'application.extensions.mailer.EMailer' );
  89. //Email configuration
  90. $mailer->SetLanguage('zh_cn');
  91. $mailer->Host = Yii::app()->params['emailHost']; //Sending mail server
  92. $mailer->Port = Yii::app()->params['emailPort']; //Mail port
  93. $mailer->Timeout = Yii::app()->params['emailTimeout'];//Email sending timeout
  94.  $mailer->ContentType = 'text/html';//Set html format
  95. $mailer->SMTPAuth = true;
  96. $mailer->Username = Yii::app()->params['emailUserName'];
  97. $mailer->Password = Yii::app()->params['emailPassword'];
  98. $mailer->IsSMTP ();
  99.  $mailer->From = $mailer->Username; // Sender’s email address
  100. $mailer->FromName = Yii::app()->params['emailFormName']; // Sender’s name
  101. $mailer->AddReplyTo ( $mailer->Username );
  102. $mailer->CharSet = 'UTF-8';
  103.  //Add email log 
  104. $modelMail = new MailLog ();
  105. $modelMail->accept = $toemail;
  106. $modelMail->subject = $subject;
  107. $modelMail->message = $message;
  108.         $modelMail->send_status = 'waiting';  
  109.         $modelMail->save ();  
  110.         // 发送邮件  
  111.         $mailer->AddAddress ( $toemail );  
  112.         $mailer->Subject = $subject;  
  113.         $mailer->Body = $message;  
  114.         if ($mailer->Send () === true) {  
  115.             $modelMail->times = $modelMail->times   1;  
  116.             $modelMail->send_status = 'success';  
  117.             $modelMail->save ();  
  118.             return true;  
  119.         } else {  
  120.             $error = $mailer->ErrorInfo;  
  121.             $modelMail->times = $modelMail->times   1;  
  122.             $modelMail->send_status = 'failed';  
  123.             $modelMail->error = $error;  
  124.             $modelMail->save ();  
  125.             return false;  
  126.         }  
  127.     }
  128. /**
  129. * Determine whether the string is utf-8 or gb2312
  130. * @param unknown $str
  131. * @param string $default
  132. * @return string
  133. */
  134. public static function utf8_gb2312($str, $default = 'gb2312')
  135. {
  136.  $str = preg_replace("/[x01-x7F] /", "", $str);
  137. if (emptyempty($str)) return $default;
  138. $preg = array(
  139.                                                                                                                                                                                conditions), this range actually includes Traditional Chinese characters
  140. ); if ($default == 'gb2312') {
  141.                                                                                              }  else {                                                                                               }  
  142. if (!preg_match($preg[$default], $str)) {
  143.         return $option; 
  144. }  
  145. $str = @iconv($default, $option, $str);
  146. //Cannot be converted to $option, indicating that the original one is not $default
  147. if (
  148. empty
  149. empty(
  150. $str)) {         return $option; 
  151. }  
  152. return $default; }  
  153.     /**
  154. * UTF-8 and gb2312 automatic conversion
  155. * @param unknown $string
  156. * @param string $outEncoding
  157. * @return unknown|string
  158. */  
  159.     public static function safeEncoding($string,$outEncoding = 'UTF-8')  
  160.     {  
  161.         $encoding = "UTF-8";  
  162.         for($i = 0; $i strlen ( $string ); $i  ) {  
  163.             if (ord ( $string {$i} ) 
  164.                 continue;  
  165.             if ((ord ( $string {$i} ) & 224) == 224) {  
  166.                 // 第一个字节判断通过  
  167.                 $char = $string {  $i};  
  168.                 if ((ord ( $char ) & 128) == 128) {  
  169.                     // 第二个字节判断通过  
  170.                     $char = $string {  $i};  
  171.                     if ((ord ( $char ) & 128) == 128) {  
  172.                         $encoding = "UTF-8";  
  173.                         break;  
  174.                     }  
  175.                 }  
  176.             }  
  177.             if ((ord ( $string {$i}) & 192) == 192) {
  178.                                                                                                                                                                                                                                                                                               $char =
  179. $string {
  180. $i};                                                                                                                                                                                                                                                                             ​ 
  181.                                                                                                                                                                                                                                                                                                      
  182.                                                                                                                                                                                                                                                                                              }  
  183. if (strtoupper ( $encoding) ==
  184. strtoupper (
  185. $outEncoding))
  186.            return 
  187. $string; 
  188.  
  189. else 
  190.  return @iconv ($encoding, $outEncoding, $string); 
  191.  } 
  192. /**
  193. * Returns all values ​​of a key name in the two-dimensional array
  194. * @param input $array * @param string $key * @return array
  195. */
  196. public static function array_key_values(
  197. $array =
  198. array(), $key='')
  199. {
  200. $ret =
  201. array();
  202.  foreach((array)$array as $k=>$v){ 
  203.    
  204. $ret[$k] = $v[$key];
  205. }   return $ret; }  
  206.     /**
  207. * Determine whether the file/directory is writable (replacing the system's own is_writeable function)
  208. * @param string $file file/directory
  209. * @return boolean
  210. */  
  211.     public static function is_writeable($file) {  
  212.         if (is_dir($file)){  
  213.             $dir = $file;  
  214.             if ($fp = @fopen("$dir/test.txt", 'w')) {  
  215.                 @fclose($fp);  
  216.                 @unlink("$dir/test.txt");  
  217.                 $writeable = 1;  
  218.             } else {  
  219.                 $writeable = 0;  
  220.             }  
  221.         } else {  
  222.             if ($fp = @fopen($file, 'a ')) {  
  223.                 @fclose($fp);  
  224.                 $writeable = 1;  
  225.             } else {  
  226.                 $writeable = 0;  
  227.             }  
  228.         }  
  229.         return $writeable;  
  230.     }  
  231.     /**
  232. * Formatting unit
  233. */  
  234.     static public function byteFormat( $size, $dec = 2 ) {  
  235.         $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );  
  236.         $pos = 0;  
  237.         while ( $size >= 1024 ) {  
  238.             $size /= 1024;  
  239.             $pos  ;  
  240.         }  
  241.         return round( $size, $dec ) . " " . $a[$pos];  
  242.     }  
  243.     /**
  244. * Drop-down box, radio button automatic selection
  245. *
  246. * @param $string Input characters
  247. * @param $param Conditions
  248. * @param $type Type
  249. * selected checked
  250. * @return string
  251. */  
  252.     static public function selected( $string, $param = 1, $type = 'select' ) {  
  253.         $true = false;  
  254.         if ( is_array( $param ) ) {  
  255.             $true = in_array( $string, $param );  
  256.         }elseif ( $string == $param ) {  
  257.             $true = true;  
  258.         }  
  259.         $return='';  
  260.         if ( $true )  
  261.             $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';  
  262.         echo $return;  
  263.     }
  264. /**
  265. * Download remote images
  266. * @param string $url The absolute url of the image
  267. * @param string $filepath The full path of the file (such as /www/images/test). This function will automatically determine the suffix name of the image based on the image URL and http header information
  268. * @param string $filename The name of the file to be saved (excluding extension)
  269. * @return mixed Returns an array describing the image information if the download is successful, false if the download fails
  270. */
  271. static public function downloadImage($url, $filepath, $filename) {
  272. //Header information returned by the server
  273. $responseHeaders = array();
  274.  //Original picture name
  275. $originalfilename = '';
  276. //The suffix name of the picture
  277. $ext = '';
  278. $ch = curl_init($url);
  279. //Set the value returned by curl_exec to include the HTTP header
  280. curl_setopt($ch, CURLOPT_HEADER, 1);
  281. //Set the value returned by curl_exec to include Http content
  282. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  283. //Set the page after crawling jump (http 301, 302)
  284. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  285. //Set the maximum number of HTTP redirects
  286. curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
  287. //Data returned by the server (including http header information and content)
  288. $html = curl_exec($ch);
  289. //Get relevant information about this crawl
  290. $httpinfo = curl_getinfo($ch);
  291. curl_close($ch);
  292. if ($html !== false) {
  293.                                                                                                        // Separate the header and body of the response. Since the server may use 302 jumps, the string needs to be separated into 2 substrings with the number of jumps
  294.                                                                                                                        🎜>
  295.  //The penultimate paragraph is the http header of the server’s last response
  296.  $header = $httpArr[count($httpArr) - 2];
  297.  //The penultimate paragraph is the content of the server’s last response
  298.  $body = $httpArr[count($httpArr) - 1];
  299.        $header.="rn"; 
  300.  //Get the header information of the last response
  301. preg_match_all('/([a-z0-9-_] ):s*([^rn] )rn/i', $header, $matches);
  302.  if (!emptyempty($matches) && count($matches) == 3 && !emptyempty( $matches[1]) && !emptyempty($matches[1])) {
  303.           for ($i = 0; $i count($matches[1]); $i ) { 
  304.               if (array_key_exists($i, $matches[2])) { 
  305.                                                                                                                                   $responseHeaders[$matches[1][$i]] = $matches[2][$i]; >                                                                                                                                                                                                            
  306.                                                                                                
  307.                                                                                                                                                                                                       
  308.  
  309. if (0 '{(?:[^/\\] ).(jpg|jpeg|gif|png|bmp)$}i',
  310. $url ,
  311. $matches)) {
  312.             $originalfilename = $matches[0];             $ext =
  313. $matches[1];
  314. }  else {  
  315.            if (array_key_exists('Content-Type',
  316. $responseHeaders)) { 
  317.                                                                                                i', $responseHeaders['Content-Type'], $extmatches)) {
  318.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
  319. //Save the file
  320.  
  321. if (!
  322. empty
  323. empty(
  324. $ext)) {
  325.                 //If the directory does not exist, you must create the directory first            if(!is_dir(
  326. $filepath)){ 
  327.                   mkdir($filepath, 0777, true);                                                                                                  
  328.           
  329. $filepath .= '/'.$filename.".$ext"; 
  330.             $local_file = fopen($filepath, 'w'); 
  331.                                                                                                                                                                                                                                   fclose($local_file);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   ,
  332. 'height' =>
  333. $sizeinfo[1], 'orginalfilename' => >$filepath, PATHINFO_BASENAME));                                                                                                                                                                                                            
  334.                                                                                                
  335. }    return false; }  
  336.     /**
  337. * Find if the IP is in a certain rank
  338. * @param string $ip The IP to be queried
  339. * @param $arrIP Banned ip
  340. * @return boolean
  341. */  
  342.     public static function ipAccess($ip='0.0.0.0', $arrIP = array()){  
  343.         $access = true;  
  344.         $ip && $arr_cur_ip = explode('.', $ip);  
  345.         foreach((array)$arrIP as $key=> $value){  
  346.             if($value == '*.*.*.*'){  
  347.                 $access = false; //禁止所有  
  348.                 break;  
  349.             }  
  350.             $tmp_arr = explode('.', $value);  
  351.             if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) {  
  352.                 //前两段相同  
  353.                 if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){  
  354.                     //第三段为* 或者相同  
  355.                     if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){  
  356.                         //第四段为* 或者相同  
  357.                         $access = false; //在禁止ip列,则禁止访问  
  358.                         break;  
  359.                     }  
  360.                 }
  361.                                                                                                
  362. }  
  363. return $access;
  364.  } 
  365. /**
  366. * @param string $string Original text or cipher text
  367. * @param string $operation operation (ENCODE | DECODE), the default is DECODE
  368. * @param string $key key
  369. * @param int $expiry Ciphertext validity period, valid when encrypted, unit seconds, 0 means permanent validity
  370. * @return string The processed original text or the cipher text processed by base64_encode
  371. *
  372. * @example
  373. *
  374. * $a = authcode('abc', 'ENCODE', 'key');
  375. * $b = authcode($a, 'DECODE', 'key'); // $b(abc)
  376. *
  377. * $a = authcode('abc', 'ENCODE', 'key', 3600);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn