Table of Contents
自己项目中PHP常用工具类大全分享,php工具类大全分享
Home php教程 php手册 自己项目中PHP常用工具类大全分享,php工具类大全分享

自己项目中PHP常用工具类大全分享,php工具类大全分享

Jun 13, 2016 am 08:41 AM
php

自己项目中PHP常用工具类大全分享,php工具类大全分享

Php代码  
  1.  /** 
  2.  * 助手类 
  3.  * @author www.shouce.ren 
  4.  * 
  5.  */  
  6.  class Helper  
  7.  {  
  8.     /** 
  9.      * 判断当前服务器系统 
  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.      * 当前微妙数 
  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.      * 切割utf-8格式的字符串(一个汉字或者字符占一个字节) 
  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.      * 遍历文件夹 
  59.      * @param string $dir 
  60.      * @param boolean $all  true表示递归遍历 
  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.         //邮件配置  
  90.         $mailer->SetLanguage('zh_cn');  
  91.         $mailer->Host = Yii::app()->params['emailHost']; //发送邮件服务器  
  92.         $mailer->Port = Yii::app()->params['emailPort']; //邮件端口  
  93.         $mailer->Timeout = Yii::app()->params['emailTimeout'];//邮件发送超时时间  
  94.         $mailer->ContentType = 'text/html';//设置html格式  
  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; // 发件人邮箱  
  100.         $mailer->FromName = Yii::app()->params['emailFormName']; // 发件人姓名  
  101.         $mailer->AddReplyTo ( $mailer->Username );  
  102.         $mailer->CharSet = 'UTF-8';  
  103.         // 添加邮件日志  
  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.      * 判断字符串是utf-8 还是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.             "gb2312" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正则判断是否是gb2312  
  140.             "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u",      //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了  
  141.         );  
  142.         if ($default == 'gb2312') {  
  143.             $option = 'utf-8';  
  144.         } else {  
  145.             $option = 'gb2312';  
  146.         }  
  147.         if (!preg_match($preg[$default], $str)) {  
  148.             return $option;  
  149.         }  
  150.         $str = @iconv($default, $option, $str);  
  151.         //不能转成 $option, 说明原来的不是 $default  
  152.         if (emptyempty($str)) {  
  153.             return $option;  
  154.         }  
  155.         return $default;  
  156.     }  
  157.     /** 
  158.      * utf-8和gb2312自动转化 
  159.      * @param unknown $string 
  160.      * @param string $outEncoding 
  161.      * @return unknown|string 
  162.      */  
  163.     public static function safeEncoding($string,$outEncoding = 'UTF-8')  
  164.     {  
  165.         $encoding = "UTF-8";  
  166.         for($i = 0; $i strlen ( $string ); $i ++) {  
  167.             if (ord ( $string {$i} ) 
  168.                 continue;  
  169.             if ((ord ( $string {$i} ) & 224) == 224) {  
  170.                 // 第一个字节判断通过  
  171.                 $char = $string {++ $i};  
  172.                 if ((ord ( $char ) & 128) == 128) {  
  173.                     // 第二个字节判断通过  
  174.                     $char = $string {++ $i};  
  175.                     if ((ord ( $char ) & 128) == 128) {  
  176.                         $encoding = "UTF-8";  
  177.                         break;  
  178.                     }  
  179.                 }  
  180.             }  
  181.             if ((ord ( $string {$i} ) & 192) == 192) {  
  182.                 // 第一个字节判断通过  
  183.                 $char = $string {++ $i};  
  184.                 if ((ord ( $char ) & 128) == 128) {  
  185.                     // 第二个字节判断通过  
  186.                     $encoding = "GB2312";  
  187.                     break;  
  188.                 }  
  189.             }  
  190.         }  
  191.         if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))  
  192.             return $string;  
  193.         else  
  194.             return @iconv ( $encoding, $outEncoding, $string );  
  195.     }  
  196.     /** 
  197.      * 返回二维数组中某个键名的所有值 
  198.      * @param input $array 
  199.      * @param string $key 
  200.      * @return array 
  201.      */  
  202.     public static function array_key_values($array =array(), $key='')  
  203.     {  
  204.         $ret = array();  
  205.         foreach((array)$array as $k=>$v){  
  206.             $ret[$k] = $v[$key];  
  207.         }  
  208.         return $ret;  
  209.     }  
  210.     /** 
  211.      * 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数) 
  212.      * @param string $file 文件/目录 
  213.      * @return boolean 
  214.      */  
  215.     public static function is_writeable($file) {  
  216.         if (is_dir($file)){  
  217.             $dir = $file;  
  218.             if ($fp = @fopen("$dir/test.txt", 'w')) {  
  219.                 @fclose($fp);  
  220.                 @unlink("$dir/test.txt");  
  221.                 $writeable = 1;  
  222.             } else {  
  223.                 $writeable = 0;  
  224.             }  
  225.         } else {  
  226.             if ($fp = @fopen($file, 'a+')) {  
  227.                 @fclose($fp);  
  228.                 $writeable = 1;  
  229.             } else {  
  230.                 $writeable = 0;  
  231.             }  
  232.         }  
  233.         return $writeable;  
  234.     }  
  235.     /** 
  236.      * 格式化单位 
  237.      */  
  238.     static public function byteFormat( $size, $dec = 2 ) {  
  239.         $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );  
  240.         $pos = 0;  
  241.         while ( $size >= 1024 ) {  
  242.             $size /= 1024;  
  243.             $pos ++;  
  244.         }  
  245.         return round( $size, $dec ) . " " . $a[$pos];  
  246.     }  
  247.     /** 
  248.      * 下拉框,单选按钮 自动选择 
  249.      * 
  250.      * @param $string 输入字符 
  251.      * @param $param  条件 
  252.      * @param $type   类型 
  253.      * selected checked 
  254.      * @return string 
  255.      */  
  256.     static public function selected( $string, $param = 1, $type = 'select' ) {  
  257.         $true = false;  
  258.         if ( is_array( $param ) ) {  
  259.             $true = in_array( $string, $param );  
  260.         }elseif ( $string == $param ) {  
  261.             $true = true;  
  262.         }  
  263.         $return='';  
  264.         if ( $true )  
  265.             $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';  
  266.         echo $return;  
  267.     }  
  268.     /** 
  269.      * 下载远程图片 
  270.      * @param string $url 图片的绝对url 
  271.      * @param string $filepath 文件的完整路径(例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名 
  272.      * @param string $filename 要保存的文件名(不含扩展名) 
  273.      * @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false 
  274.      */  
  275.     static public function downloadImage($url, $filepath, $filename) {  
  276.         //服务器返回的头信息  
  277.         $responseHeaders = array();  
  278.         //原始图片名  
  279.         $originalfilename = '';  
  280.         //图片的后缀名  
  281.         $ext = '';  
  282.         $ch = curl_init($url);  
  283.         //设置curl_exec返回的值包含Http头  
  284.         curl_setopt($ch, CURLOPT_HEADER, 1);  
  285.         //设置curl_exec返回的值包含Http内容  
  286.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
  287.         //设置抓取跳转(http 301,302)后的页面  
  288.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
  289.         //设置最多的HTTP重定向的数量  
  290.         curl_setopt($ch, CURLOPT_MAXREDIRS, 3);  
  291.         //服务器返回的数据(包括http头信息和内容)  
  292.         $html = curl_exec($ch);  
  293.         //获取此次抓取的相关信息  
  294.         $httpinfo = curl_getinfo($ch);  
  295.         curl_close($ch);  
  296.         if ($html !== false) {  
  297.             //分离response的header和body,由于服务器可能使用了302跳转,所以此处需要将字符串分离为 2+跳转次数 个子串  
  298.             $httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);  
  299.             //倒数第二段是服务器最后一次response的http头  
  300.             $header = $httpArr[count($httpArr) - 2];  
  301.             //倒数第一段是服务器最后一次response的内容  
  302.             $body = $httpArr[count($httpArr) - 1];  
  303.             $header.="\r\n";  
  304.             //获取最后一次response的header信息  
  305.             preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);  
  306.             if (!emptyempty($matches) && count($matches) == 3 && !emptyempty($matches[1]) && !emptyempty($matches[1])) {  
  307.                 for ($i = 0; $i count($matches[1]); $i++) {  
  308.                     if (array_key_exists($i, $matches[2])) {  
  309.                         $responseHeaders[$matches[1][$i]] = $matches[2][$i];  
  310.                     }  
  311.                 }  
  312.             }  
  313.             //获取图片后缀名  
  314.             if (0 '{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {  
  315.                 $originalfilename = $matches[0];  
  316.                 $ext = $matches[1];  
  317.             } else {  
  318.                 if (array_key_exists('Content-Type', $responseHeaders)) {  
  319.                     if (0 '{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) {  
  320.                         $ext = $extmatches[1];  
  321.                     }  
  322.                 }  
  323.             }  
  324.             //保存文件  
  325.             if (!emptyempty($ext)) {  
  326.                 //如果目录不存在,则先要创建目录  
  327.                 if(!is_dir($filepath)){  
  328.                     mkdir($filepath, 0777, true);  
  329.                 }  
  330.                 $filepath .= '/'.$filename.".$ext";  
  331.                 $local_file = fopen($filepath, 'w');  
  332.                 if (false !== $local_file) {  
  333.                     if (false !== fwrite($local_file, $body)) {  
  334.                         fclose($local_file);  
  335.                         $sizeinfo = getimagesize($filepath);  
  336.                         return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));  
  337.                     }  
  338.                 }  
  339.             }  
  340.         }  
  341.         return false;  
  342.     }  
  343.     /** 
  344.      * 查找ip是否在某个段位里面 
  345.      * @param string $ip 要查询的ip 
  346.      * @param $arrIP     禁止的ip 
  347.      * @return boolean 
  348.      */  
  349.     public static function ipAccess($ip='0.0.0.0', $arrIP = array()){  
  350.         $access = true;  
  351.         $ip && $arr_cur_ip = explode('.', $ip);  
  352.         foreach((array)$arrIP as $key=> $value){  
  353.             if($value == '*.*.*.*'){  
  354.                 $access = false; //禁止所有  
  355.                 break;  
  356.             }  
  357.             $tmp_arr = explode('.', $value);  
  358.             if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) {  
  359.                 //前两段相同  
  360.                 if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){  
  361.                     //第三段为* 或者相同  
  362.                     if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){  
  363.                         //第四段为* 或者相同  
  364.                         $access = false; //在禁止ip列,则禁止访问  
  365.                         break;  
  366.                     }  
  367.                 }  
  368.             }  
  369.         }  
  370.         return $access;  
  371.     }  
  372.     /** 
  373.      * @param string $string 原文或者密文 
  374.      * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE 
  375.      * @param string $key 密钥 
  376.      * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效 
  377.      * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文 
  378.      * 
  379.      * @example 
  380.      * 
  381.      * $a = authcode('abc', 'ENCODE', 'key'); 
  382.      * $b = authcode($a, 'DECODE', 'key');  // $b(abc) 
  383.      * 
  384.      * $a = authcode('abc', 'ENCODE', 'key', 3600); 
  385.      * $b = authcode('abc', 'DECODE
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles