목차
自己项目中PHP常用工具类大全分享,php工具类大全分享
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
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP 데이터베이스 작업 CakePHP 데이터베이스 작업 Sep 10, 2024 pm 05:25 PM

CakePHP에서 데이터베이스 작업은 매우 쉽습니다. 이번 장에서는 CRUD(생성, 읽기, 업데이트, 삭제) 작업을 이해하겠습니다.

CakePHP 날짜 및 시간 CakePHP 날짜 및 시간 Sep 10, 2024 pm 05:27 PM

cakephp4에서 날짜와 시간을 다루기 위해 사용 가능한 FrozenTime 클래스를 활용하겠습니다.

CakePHP 파일 업로드 CakePHP 파일 업로드 Sep 10, 2024 pm 05:27 PM

파일 업로드 작업을 위해 양식 도우미를 사용할 것입니다. 다음은 파일 업로드의 예입니다.

CakePHP 토론 CakePHP 토론 Sep 10, 2024 pm 05:28 PM

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

CakePHP 유효성 검사기 만들기 CakePHP 유효성 검사기 만들기 Sep 10, 2024 pm 05:26 PM

컨트롤러에 다음 두 줄을 추가하면 유효성 검사기를 만들 수 있습니다.

CakePHP 로깅 CakePHP 로깅 Sep 10, 2024 pm 05:26 PM

CakePHP에 로그인하는 것은 매우 쉬운 작업입니다. 한 가지 기능만 사용하면 됩니다. cronjob과 같은 백그라운드 프로세스에 대해 오류, 예외, 사용자 활동, 사용자가 취한 조치를 기록할 수 있습니다. CakePHP에 데이터를 기록하는 것은 쉽습니다. log() 함수는 다음과 같습니다.

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

See all articles