Home Backend Development PHP Tutorial 自各儿项目中PHP常用工具类大全分享

自各儿项目中PHP常用工具类大全分享

Jun 13, 2016 pm 12:29 PM
nbsp param return string

自己项目中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', 'key'); // 在一个小时内,$b(abc),否则 $b 为空 
  386.      */  
  387.     public 
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)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

OOBELANGUAGE Error Problems in Windows 11/10 Repair OOBELANGUAGE Error Problems in Windows 11/10 Repair Jul 16, 2023 pm 03:29 PM

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

How to Fix Activation Error Code 0xc004f069 in Windows Server How to Fix Activation Error Code 0xc004f069 in Windows Server Jul 22, 2023 am 09:49 AM

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using

See all articles