Table of Contents
1. Month display" >1. Month display
2. Filter strings and retain UTF8 alphanumeric Chinese and some symbols" >2. Filter strings and retain UTF8 alphanumeric Chinese and some symbols
3. Binary stream generation file" >3. Binary stream generation file
4. Forced update of image cache" >4. Forced update of image cache
5. Convert files to base64 and convert files with base64" >5. Convert files to base64 and convert files with base64
6. Convert hexadecimal color to decimal System color" >6. Convert hexadecimal color to decimal System color
7. Get the difference time between two time periods" >7. Get the difference time between two time periods
8. Delayed output content" >8. Delayed output content
9. Use XOR (xor) key to encrypt and decrypt files" >9. Use XOR (xor) key to encrypt and decrypt files
10. Get the owner, group user, and permissions of the file or folder " >10. Get the owner, group user, and permissions of the file or folder
11. Delete empty directories and empty subdirectories " >11. Delete empty directories and empty subdirectories
12. Unicode to Chinese" >12. Unicode to Chinese
Home Backend Development PHP Tutorial How to use php common custom methods

How to use php common custom methods

Jun 09, 2018 pm 02:53 PM
function php

1. Month display

/** 月份顯示
*   @param  int    $m       1-12
*   @param  int    $type    0:long 1:short(default) 2:chinese
*   @return String
*/
function format_month($m, $type=0){
    $month = array(
                array('', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
                array('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'),
                array('', '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')
            );
    return $month[$type][$m];
}
Copy after login

2. Filter strings and retain UTF8 alphanumeric Chinese and some symbols

/** 過濾字符串,保留UTF8字母數字中文及部份符號
*   @param  String  $ostr
*   @return String
*/
function filter_utf8_char($ostr){
    preg_match_all('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $ostr, $matches);
    $str = join('', $matches[0]);
    if($str==''){   //含有特殊字符需要逐個處理
        $returnstr = '';
        $i = 0;
        $str_length = strlen($ostr);
        while ($i<=$str_length){
            $temp_str = substr($ostr, $i, 1);
            $ascnum = Ord($temp_str);
            if ($ascnum>=224){
                $returnstr = $returnstr.substr($ostr, $i, 3);
                $i = $i + 3;
            }elseif ($ascnum>=192){
                $returnstr = $returnstr.substr($ostr, $i, 2);
                $i = $i + 2;
            }elseif ($ascnum>=65 && $ascnum<=90){
                $returnstr = $returnstr.substr($ostr, $i, 1);
                $i = $i + 1;
            }elseif ($ascnum>=128 && $ascnum<=191){ // 特殊字符
                $i = $i + 1;
            }else{
                $returnstr = $returnstr.substr($ostr, $i, 1);
                $i = $i + 1;
            }
        }
        $str = $returnstr;
        preg_match_all(&#39;/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u&#39;, $str, $matches);
        $str = join(&#39;&#39;, $matches[0]);
    }
    return $str;
}
Copy after login

3. Binary stream generation file

/** 二进制流生成文件
*   $_POST 无法解释二进制流,需要用到 $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;] 或 php://input
*   $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;] 和 php://input 都不能用于 enctype=multipart/form-data
*   @param    String    $file   要生成的文件路径
*   @return   boolean
*/
function binary_to_file($file){
    $content = $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;];  // 需要php.ini设置
    if(empty($content)){
        $content = file_get_contents(&#39;php://input&#39;);    // 不需要php.ini设置,内存压力小
    }
    $ret = file_put_contents($file, $content, true);
    return $ret;
}
Copy after login

4. Forced update of image cache

/** 強制更新圖片緩存
*   @param Array $files 要更新的圖片
*   @param int $version 版本
*/
function force_reload_file($files=array(), $version=0){
    $html = &#39;&#39;;
    if(!isset($_COOKIE[&#39;force_reload_page_&#39;.$version])){ // 判斷是否已更新過
        setcookie(&#39;force_reload_page_&#39;.$version, true, time()+2592000);
        $html .= &#39;<script type="text/javascript">&#39;."\r\n";
        $html .= &#39;window.onload = function(){&#39;."\r\n";
        $html .= &#39;setTimeout(function(){window.location.reload(true); },1000);&#39;."\r\n";
        $html .= &#39;}&#39;."\r\n";
        $html .= &#39;</script>&#39;;
        echo $html;
        exit();
    }else{  // 讀取圖片一次,針對chrome優化
        if($files){
            $html .= &#39;<script type="text/javascript">&#39;."\r\n";
            $html .= "<!--\r\n";
            for($i=0,$max=count($files); $i<$max; $i++){
                $html .= &#39;var force_reload_file_&#39;.$i.&#39; =new Image()&#39;."\r\n";
                $html .= &#39;force_reload_file_&#39;.$i.&#39;.src="&#39;.$files[$i].&#39;"&#39;."\r\n";
            }
            $html .= "-->\r\n";
            $html .= &#39;</script>&#39;;
        }
    }
    return $html;
}
Copy after login

5. Convert files to base64 and convert files with base64

/** 文件转base64输出
* @param  String $file 文件路径
* @return String base64 string
*/
function fileToBase64($file){
    $base64_file = &#39;&#39;;
    if(file_exists($file)){
        $mime_type = mime_content_type($file);
        $base64_data = base64_encode(file_get_contents($file));
        $base64_file = &#39;data:&#39;.$mime_type.&#39;;base64,&#39;.$base64_data;
    }
    return $base64_file;
}
/** base64转文件输出
* @param  String $base64_data base64数据
* @param  String $file        要保存的文件路径
* @return boolean
*/
function base64ToFile($base64_data, $file){
    if(!$base64_data || !$file){
        return false;
    }
    return file_put_contents($file, base64_decode($base64_data), true);
}
Copy after login

6. Convert hexadecimal color to decimal System color

/** 16进制颜色转10进制颜色,例#FF0000转rgb(255, 0, 0);
* @param  String $hexcolor
* @return Array
*/
function hex2rgb($hexcolor){
    $color = str_replace(&#39;#&#39;, &#39;&#39;, $hexcolor);
    if (strlen($color) > 3) {
        $rgb = array(
            &#39;r&#39; => hexdec(substr($color, 0, 2)),
            &#39;g&#39; => hexdec(substr($color, 2, 2)),
            &#39;b&#39; => hexdec(substr($color, 4, 2))
        );
    } else {
        $r = substr($color, 0, 1) . substr($color, 0, 1);
        $g = substr($color, 1, 1) . substr($color, 1, 1);
        $b = substr($color, 2, 1) . substr($color, 2, 1);
        $rgb = array(
            &#39;r&#39; => hexdec($r),
            &#39;g&#39; => hexdec($g),
            &#39;b&#39; => hexdec($b)
        );
    }
    return $rgb;
}
Copy after login

7. Get the difference time between two time periods

/** 获取两时间段相差时间
* @param datetime $starttime
* @param datetime $endtime
* @return String
*/
function diff_time($starttime, $endtime){
    $diff = abs(strtotime($starttime) - strtotime($endtime));
    $days = (int)($diff/86400);
    $hours = (int)($diff/3600);
    if($days>0){
        $ret = $days.&#39; 天&#39;;
    }elseif($hours>0){
        $ret = $hours.&#39; 小时&#39;;
    }else{
        $ret = &#39;不足1小时&#39;;
    }
    return $ret;
}
Copy after login

8. Delayed output content

/** 延时输出内容
* @param int $sec 秒数,可以是小数例如 0.3
*/
function cache_flush($sec=2){
    ob_flush();
    flush();
    usleep($sec*1000000);
}
Copy after login

9. Use XOR (xor) key to encrypt and decrypt files

/** 文件加密,使用key与原文异或(XOR)生成密文,解密则再执行一次异或即可
* @param String $source 要加密或解密的文件
* @param String $dest   加密或解密后的文件
* @param String $key    密钥
*/
function file_encrypt($source, $dest, $key){
	if(file_exists($source)){
		
		$content = &#39;&#39;;          // 处理后的字符串
		$keylen = strlen($key); // 密钥长度
		$index = 0;
		$fp = fopen($source, &#39;rb&#39;);
		while(!feof($fp)){
			$tmp = fread($fp, 1);
			$content .= $tmp ^ substr($key,$index%$keylen,1);
			$index++;
		}
		fclose($fp);
		return file_put_contents($dest, $content, true);
	}else{
		return false;
	}
}
Copy after login

10. Get the owner, group user, and permissions of the file or folder

/** 获取文件或文件夹的拥有者,组用户,及权限
* @param  String $filename
* @return Array
*/
function file_attribute($filename){
    if(!file_exists($filename)){
        return false;
    }
    $owner = posix_getpwuid(fileowner($filename));
    $group = posix_getpwuid(filegroup($filename));
    $perms = substr(sprintf(&#39;%o&#39;,fileperms($filename)),-4);
    $ret = array(
        &#39;owner&#39; => $owner[&#39;name&#39;],
        &#39;group&#39; => $group[&#39;name&#39;],
        &#39;perms&#39; => $perms
    );
    return $ret;
}
Copy after login

11. Delete empty directories and empty subdirectories

/** 删除所有空目录
* @param String $path 目录路径
*/
function rm_empty_dir($path){
    if($handle = opendir($path)){
        while(($file=readdir($handle))!==false){     // 遍历文件夹
            if($file!=&#39;.&#39; && $file!=&#39;..&#39;){
                $curfile = $path.&#39;/&#39;.$file;          // 当前目录
                if(is_dir($curfile)){                // 目录
                    rm_empty_dir($curfile);          // 如果是目录则继续遍历
                    if(count(scandir($curfile))==2){ // 目录为空,=2是因为. 和 ..存在
                        rmdir($curfile);             // 删除空目录
                    }
                }
            }
        }
        closedir($handle);
    }
}
Copy after login

12. Unicode to Chinese

/* unicode 转 中文
* @param  String $str unicode 字符串
* @return String
*/
function unescape($str) {
    $str = rawurldecode($str);
    preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
    $ar = $r[0];
    foreach($ar as $k=>$v) {
        if(substr($v,0,2) == "%u"){
            $ar[$k] = iconv("UCS-2BE","UTF-8",pack("H4",substr($v,-4)));
        }elseif(substr($v,0,3) == "&#x"){
            $ar[$k] = iconv("UCS-2BE","UTF-8",pack("H4",substr($v,3,-1)));
        }elseif(substr($v,0,2) == "&#") {
            $ar[$k] = iconv("UCS-2BE","UTF-8",pack("n",substr($v,2,-1)));
        }
    }
    return join("",$ar);
}
Copy after login

This article introduces common customization methods using php. For more related content, please Follow php Chinese website.

Related recommendations:

How to encrypt/decrypt files using XOR (XOR) through php

How to obtain through php The name of a variable

Learn about PHP object cloning clone

The above is the detailed content of How to use php common custom methods. For more information, please follow other related articles on the PHP Chinese website!

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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,

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

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.

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.

See all articles