自己项目中PHP常用工具类大全分享,php工具类大全分享
Php代码- /**
- * 助手类
- * @author www.shouce.ren
- *
- */
- class Helper
- {
- /**
- * 判断当前服务器系统
- * @return string
- */
- public static function getOS(){
- if(PATH_SEPARATOR == ':'){
- return 'Linux';
- }else{
- return 'Windows';
- }
- }
- /**
- * 当前微妙数
- * @return number
- */
- public static function microtime_float() {
- list ( $usec, $sec ) = explode ( " ", microtime () );
- return (( float ) $usec + ( float ) $sec);
- }
- /**
- * 切割utf-8格式的字符串(一个汉字或者字符占一个字节)
- *
- * @author zhao jinhan
- * @version v1.0.0
- *
- */
- public static function truncate_utf8_string($string, $length, $etc = '...') {
- $result = '';
- $string = html_entity_decode ( trim ( strip_tags ( $string ) ), ENT_QUOTES, 'UTF-8' );
- $strlen = strlen ( $string );
- for($i = 0; (($i $strlen) && ($length > 0)); $i ++) {
- if ($number = strpos ( str_pad ( decbin ( ord ( substr ( $string, $i, 1 ) ) ), 8, '0', STR_PAD_LEFT ), '0' )) {
- if ($length
- break;
- }
- $result .= substr ( $string, $i, $number );
- $length -= 1.0;
- $i += $number - 1;
- } else {
- $result .= substr ( $string, $i, 1 );
- $length -= 0.5;
- }
- }
- $result = htmlspecialchars ( $result, ENT_QUOTES, 'UTF-8' );
- if ($i $strlen) {
- $result .= $etc;
- }
- return $result;
- }
- /**
- * 遍历文件夹
- * @param string $dir
- * @param boolean $all true表示递归遍历
- * @return array
- */
- public static function scanfDir($dir='', $all = false, &$ret = array()){
- if ( false !== ($handle = opendir ( $dir ))) {
- while ( false !== ($file = readdir ( $handle )) ) {
- if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) {
- $cur_path = $dir . '/' . $file;
- if (is_dir ( $cur_path )) {
- $ret['dirs'][] =$cur_path;
- $all && self::scanfDir( $cur_path, $all, $ret);
- } else {
- $ret ['files'] [] = $cur_path;
- }
- }
- }
- closedir ( $handle );
- }
- return $ret;
- }
- /**
- * 邮件发送
- * @param string $toemail
- * @param string $subject
- * @param string $message
- * @return boolean
- */
- public static function sendMail($toemail = '', $subject = '', $message = '') {
- $mailer = Yii::createComponent ( 'application.extensions.mailer.EMailer' );
- //邮件配置
- $mailer->SetLanguage('zh_cn');
- $mailer->Host = Yii::app()->params['emailHost']; //发送邮件服务器
- $mailer->Port = Yii::app()->params['emailPort']; //邮件端口
- $mailer->Timeout = Yii::app()->params['emailTimeout'];//邮件发送超时时间
- $mailer->ContentType = 'text/html';//设置html格式
- $mailer->SMTPAuth = true;
- $mailer->Username = Yii::app()->params['emailUserName'];
- $mailer->Password = Yii::app()->params['emailPassword'];
- $mailer->IsSMTP ();
- $mailer->From = $mailer->Username; // 发件人邮箱
- $mailer->FromName = Yii::app()->params['emailFormName']; // 发件人姓名
- $mailer->AddReplyTo ( $mailer->Username );
- $mailer->CharSet = 'UTF-8';
- // 添加邮件日志
- $modelMail = new MailLog ();
- $modelMail->accept = $toemail;
- $modelMail->subject = $subject;
- $modelMail->message = $message;
- $modelMail->send_status = 'waiting';
- $modelMail->save ();
- // 发送邮件
- $mailer->AddAddress ( $toemail );
- $mailer->Subject = $subject;
- $mailer->Body = $message;
- if ($mailer->Send () === true) {
- $modelMail->times = $modelMail->times + 1;
- $modelMail->send_status = 'success';
- $modelMail->save ();
- return true;
- } else {
- $error = $mailer->ErrorInfo;
- $modelMail->times = $modelMail->times + 1;
- $modelMail->send_status = 'failed';
- $modelMail->error = $error;
- $modelMail->save ();
- return false;
- }
- }
- /**
- * 判断字符串是utf-8 还是gb2312
- * @param unknown $str
- * @param string $default
- * @return string
- */
- public static function utf8_gb2312($str, $default = 'gb2312')
- {
- $str = preg_replace("/[\x01-\x7F]+/", "", $str);
- if (emptyempty($str)) return $default;
- $preg = array(
- "gb2312" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正则判断是否是gb2312
- "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u", //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了
- );
- if ($default == 'gb2312') {
- $option = 'utf-8';
- } else {
- $option = 'gb2312';
- }
- if (!preg_match($preg[$default], $str)) {
- return $option;
- }
- $str = @iconv($default, $option, $str);
- //不能转成 $option, 说明原来的不是 $default
- if (emptyempty($str)) {
- return $option;
- }
- return $default;
- }
- /**
- * utf-8和gb2312自动转化
- * @param unknown $string
- * @param string $outEncoding
- * @return unknown|string
- */
- public static function safeEncoding($string,$outEncoding = 'UTF-8')
- {
- $encoding = "UTF-8";
- for($i = 0; $i strlen ( $string ); $i ++) {
- if (ord ( $string {$i} )
- continue;
- if ((ord ( $string {$i} ) & 224) == 224) {
- // 第一个字节判断通过
- $char = $string {++ $i};
- if ((ord ( $char ) & 128) == 128) {
- // 第二个字节判断通过
- $char = $string {++ $i};
- if ((ord ( $char ) & 128) == 128) {
- $encoding = "UTF-8";
- break;
- }
- }
- }
- if ((ord ( $string {$i} ) & 192) == 192) {
- // 第一个字节判断通过
- $char = $string {++ $i};
- if ((ord ( $char ) & 128) == 128) {
- // 第二个字节判断通过
- $encoding = "GB2312";
- break;
- }
- }
- }
- if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))
- return $string;
- else
- return @iconv ( $encoding, $outEncoding, $string );
- }
- /**
- * 返回二维数组中某个键名的所有值
- * @param input $array
- * @param string $key
- * @return array
- */
- public static function array_key_values($array =array(), $key='')
- {
- $ret = array();
- foreach((array)$array as $k=>$v){
- $ret[$k] = $v[$key];
- }
- return $ret;
- }
- /**
- * 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数)
- * @param string $file 文件/目录
- * @return boolean
- */
- public static function is_writeable($file) {
- if (is_dir($file)){
- $dir = $file;
- if ($fp = @fopen("$dir/test.txt", 'w')) {
- @fclose($fp);
- @unlink("$dir/test.txt");
- $writeable = 1;
- } else {
- $writeable = 0;
- }
- } else {
- if ($fp = @fopen($file, 'a+')) {
- @fclose($fp);
- $writeable = 1;
- } else {
- $writeable = 0;
- }
- }
- return $writeable;
- }
- /**
- * 格式化单位
- */
- static public function byteFormat( $size, $dec = 2 ) {
- $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );
- $pos = 0;
- while ( $size >= 1024 ) {
- $size /= 1024;
- $pos ++;
- }
- return round( $size, $dec ) . " " . $a[$pos];
- }
- /**
- * 下拉框,单选按钮 自动选择
- *
- * @param $string 输入字符
- * @param $param 条件
- * @param $type 类型
- * selected checked
- * @return string
- */
- static public function selected( $string, $param = 1, $type = 'select' ) {
- $true = false;
- if ( is_array( $param ) ) {
- $true = in_array( $string, $param );
- }elseif ( $string == $param ) {
- $true = true;
- }
- $return='';
- if ( $true )
- $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';
- echo $return;
- }
- /**
- * 下载远程图片
- * @param string $url 图片的绝对url
- * @param string $filepath 文件的完整路径(例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名
- * @param string $filename 要保存的文件名(不含扩展名)
- * @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false
- */
- static public function downloadImage($url, $filepath, $filename) {
- //服务器返回的头信息
- $responseHeaders = array();
- //原始图片名
- $originalfilename = '';
- //图片的后缀名
- $ext = '';
- $ch = curl_init($url);
- //设置curl_exec返回的值包含Http头
- curl_setopt($ch, CURLOPT_HEADER, 1);
- //设置curl_exec返回的值包含Http内容
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- //设置抓取跳转(http 301,302)后的页面
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
- //设置最多的HTTP重定向的数量
- curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
- //服务器返回的数据(包括http头信息和内容)
- $html = curl_exec($ch);
- //获取此次抓取的相关信息
- $httpinfo = curl_getinfo($ch);
- curl_close($ch);
- if ($html !== false) {
- //分离response的header和body,由于服务器可能使用了302跳转,所以此处需要将字符串分离为 2+跳转次数 个子串
- $httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);
- //倒数第二段是服务器最后一次response的http头
- $header = $httpArr[count($httpArr) - 2];
- //倒数第一段是服务器最后一次response的内容
- $body = $httpArr[count($httpArr) - 1];
- $header.="\r\n";
- //获取最后一次response的header信息
- preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);
- if (!emptyempty($matches) && count($matches) == 3 && !emptyempty($matches[1]) && !emptyempty($matches[1])) {
- for ($i = 0; $i count($matches[1]); $i++) {
- if (array_key_exists($i, $matches[2])) {
- $responseHeaders[$matches[1][$i]] = $matches[2][$i];
- }
- }
- }
- //获取图片后缀名
- if (0 '{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {
- $originalfilename = $matches[0];
- $ext = $matches[1];
- } else {
- if (array_key_exists('Content-Type', $responseHeaders)) {
- if (0 '{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) {
- $ext = $extmatches[1];
- }
- }
- }
- //保存文件
- if (!emptyempty($ext)) {
- //如果目录不存在,则先要创建目录
- if(!is_dir($filepath)){
- mkdir($filepath, 0777, true);
- }
- $filepath .= '/'.$filename.".$ext";
- $local_file = fopen($filepath, 'w');
- if (false !== $local_file) {
- if (false !== fwrite($local_file, $body)) {
- fclose($local_file);
- $sizeinfo = getimagesize($filepath);
- return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));
- }
- }
- }
- }
- return false;
- }
- /**
- * 查找ip是否在某个段位里面
- * @param string $ip 要查询的ip
- * @param $arrIP 禁止的ip
- * @return boolean
- */
- public static function ipAccess($ip='0.0.0.0', $arrIP = array()){
- $access = true;
- $ip && $arr_cur_ip = explode('.', $ip);
- foreach((array)$arrIP as $key=> $value){
- if($value == '*.*.*.*'){
- $access = false; //禁止所有
- break;
- }
- $tmp_arr = explode('.', $value);
- if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) {
- //前两段相同
- if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){
- //第三段为* 或者相同
- if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){
- //第四段为* 或者相同
- $access = false; //在禁止ip列,则禁止访问
- break;
- }
- }
- }
- }
- return $access;
- }
- /**
- * @param string $string 原文或者密文
- * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
- * @param string $key 密钥
- * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效
- * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
- *
- * @example
- *
- * $a = authcode('abc', 'ENCODE', 'key');
- * $b = authcode($a, 'DECODE', 'key'); // $b(abc)
- *
- * $a = authcode('abc', 'ENCODE', 'key', 3600);
- * $b = authcode('abc', 'DECODE

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Linux new version
SublimeText3 Linux latest version
