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]; }
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('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $str, $matches); $str = join('', $matches[0]); } return $str; }
3. Binary stream generation file
/** 二进制流生成文件 * $_POST 无法解释二进制流,需要用到 $GLOBALS['HTTP_RAW_POST_DATA'] 或 php://input * $GLOBALS['HTTP_RAW_POST_DATA'] 和 php://input 都不能用于 enctype=multipart/form-data * @param String $file 要生成的文件路径 * @return boolean */ function binary_to_file($file){ $content = $GLOBALS['HTTP_RAW_POST_DATA']; // 需要php.ini设置 if(empty($content)){ $content = file_get_contents('php://input'); // 不需要php.ini设置,内存压力小 } $ret = file_put_contents($file, $content, true); return $ret; }
4. Forced update of image cache
/** 強制更新圖片緩存 * @param Array $files 要更新的圖片 * @param int $version 版本 */ function force_reload_file($files=array(), $version=0){ $html = ''; if(!isset($_COOKIE['force_reload_page_'.$version])){ // 判斷是否已更新過 setcookie('force_reload_page_'.$version, true, time()+2592000); $html .= '<script type="text/javascript">'."\r\n"; $html .= 'window.onload = function(){'."\r\n"; $html .= 'setTimeout(function(){window.location.reload(true); },1000);'."\r\n"; $html .= '}'."\r\n"; $html .= '</script>'; echo $html; exit(); }else{ // 讀取圖片一次,針對chrome優化 if($files){ $html .= '<script type="text/javascript">'."\r\n"; $html .= "<!--\r\n"; for($i=0,$max=count($files); $i<$max; $i++){ $html .= 'var force_reload_file_'.$i.' =new Image()'."\r\n"; $html .= 'force_reload_file_'.$i.'.src="'.$files[$i].'"'."\r\n"; } $html .= "-->\r\n"; $html .= '</script>'; } } return $html; }
5. Convert files to base64 and convert files with base64
/** 文件转base64输出 * @param String $file 文件路径 * @return String base64 string */ function fileToBase64($file){ $base64_file = ''; if(file_exists($file)){ $mime_type = mime_content_type($file); $base64_data = base64_encode(file_get_contents($file)); $base64_file = 'data:'.$mime_type.';base64,'.$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); }
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('#', '', $hexcolor); if (strlen($color) > 3) { $rgb = array( 'r' => hexdec(substr($color, 0, 2)), 'g' => hexdec(substr($color, 2, 2)), 'b' => 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( 'r' => hexdec($r), 'g' => hexdec($g), 'b' => hexdec($b) ); } return $rgb; }
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.' 天'; }elseif($hours>0){ $ret = $hours.' 小时'; }else{ $ret = '不足1小时'; } return $ret; }
8. Delayed output content
/** 延时输出内容 * @param int $sec 秒数,可以是小数例如 0.3 */ function cache_flush($sec=2){ ob_flush(); flush(); usleep($sec*1000000); }
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 = ''; // 处理后的字符串 $keylen = strlen($key); // 密钥长度 $index = 0; $fp = fopen($source, 'rb'); 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; } }
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('%o',fileperms($filename)),-4); $ret = array( 'owner' => $owner['name'], 'group' => $group['name'], 'perms' => $perms ); return $ret; }
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!='.' && $file!='..'){ $curfile = $path.'/'.$file; // 当前目录 if(is_dir($curfile)){ // 目录 rm_empty_dir($curfile); // 如果是目录则继续遍历 if(count(scandir($curfile))==2){ // 目录为空,=2是因为. 和 ..存在 rmdir($curfile); // 删除空目录 } } } } closedir($handle); } }
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); }
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!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


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

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
