Sharing of commonly used PHP operation functions

小云云
Release: 2023-03-21 09:52:01
Original
1232 people have browsed it


1. PHP encryption and decryption

PHP encryption and decryption functions can be used to encrypt some useful strings and store them in the database, and through reversible decryption of the strings, the The function uses base64 and MD5 encryption and decryption.

function encryptDecrypt($key, $string, $decrypt){ if($decrypt){ $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12"); return $decrypted; }else{ $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key)))); return $encrypted; } }
Copy after login

The usage method is as follows:

//以下是将字符串“Helloweba欢迎您”分别加密和解密 //加密: echo encryptDecrypt('password', 'Helloweba欢迎您',0); //解密: echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);
Copy after login

2. PHP generates random strings

When we need to generate a random name, temporary password and other strings, we can use the following Function:

function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; }
Copy after login

The usage method is as follows:

echo generateRandomString(20);
Copy after login

3. PHP gets the file extension (suffix)

The following function can quickly get the file extension, that is, the suffix.

function getExtension($filename){ $myext = substr($filename, strrpos($filename, '.')); return str_replace('.','',$myext); }
Copy after login

The usage method is as follows:

$filename = '我的文档.doc'; echo getExtension($filename);
Copy after login

4. PHP gets the file size and formats it

The function used below can get the file size and convert it into KB that is easy to read. , MB and other formats.

function formatSize($size) { $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); if ($size == 0) { return('n/a'); } else { return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); } }
Copy after login

The usage method is as follows:

$thefile = filesize('test_file.mp3'); echo formatSize($thefile);
Copy after login

5. PHP replace tag characters

Sometimes we need to replace strings and template tags with specified content, you can use the following Function:

function stringParser($string,$replacer){ $result = str_replace(array_keys($replacer), array_values($replacer),$string); return $result; }
Copy after login

The usage is as follows:

$string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself'; $replace_array = array('{b}' => '','{/b}' => '','{br}' => '
'); echo stringParser($string,$replace_array);
Copy after login

6. PHP lists the file names in the directory

If you want to list all the files in the directory, use the following code That’s it:

function listDirFiles($DirPath){ if($dir = opendir($DirPath)){ while(($file = readdir($dir))!== false){ if(!is_dir($DirPath.$file)) { echo "filename: $file
"; } } } }
Copy after login

The usage is as follows:

listDirFiles('home/some_folder/');
Copy after login

7. PHP gets the URL of the current page

The following function can get the URL of the current page, whether it is http or https:

function curPageURL() { $pageURL = 'http'; if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; }
Copy after login

The usage method is as follows:

echo curPageURL();
Copy after login

8. PHP forced download of files

Sometimes we don’t want the browser to directly open files, such as PDF files, but to download files directly, Then the following function can force the file to be downloaded. The application/octet-stream header type is used in the function.

function download($filename){ if ((isset($filename))&&(file_exists($filename))){ header("Content-length: ".filesize($filename)); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $filename . '"'); readfile("$filename"); } else { echo "Looks like file does not exist!"; } }
Copy after login

The usage method is as follows:

download('/down/test_45f73e852.zip');
Copy after login

9. PHP intercepts the string length

We often encounter situations where we need to intercept the length of a string (including Chinese characters), such as The title cannot exceed how many characters. The excess length is represented by.... The following function can meet your needs.

/* Utf-8、gb2312都支持的汉字截取函数 cut_str(字符串, 截取长度, 开始长度, 编码); 编码默认为 utf-8 开始长度默认为 0 */ function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){ if($code == 'UTF-8'){ $pa = "/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/"; preg_match_all($pa, $string, $t_string); if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."..."; return join('', array_slice($t_string[0], $start, $sublen)); }else{ $start = $start*2; $sublen = $sublen*2; $strlen = strlen($string); $tmpstr = ''; for($i=0; $i<$strlen; $i++){ if($i>=$start && $i<($start+$sublen)){ if(ord(substr($string, $i, 1))>129){ $tmpstr.= substr($string, $i, 2); }else{ $tmpstr.= substr($string, $i, 1); } } if(ord(substr($string, $i, 1))>129) $i++; } if(strlen($tmpstr)<$strlen ) $tmpstr.= "..."; return $tmpstr; } }
Copy after login

The usage method is as follows:

$str = "jQuery插件实现的加载图片和页面效果"; echo cutStr($str,16);
Copy after login

10. PHP gets the real IP of the client

We often use the database to record the user’s IP. The following code can get the real IP of the client. IP:

//获取用户真实IP function getIp() { if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) $ip = getenv("HTTP_CLIENT_IP"); else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR"); else if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR']; else $ip = "unknown"; return ($ip); }
Copy after login

The usage method is as follows:

echo getIp();
Copy after login

11. PHP prevents SQL injection

When we query the database, for security reasons, we need to filter some illegal characters to prevent SQL For malicious injection, please take a look at the function:

function injCheck($sql_str) { $check = preg_match('/select|insert|update|delete|'|/*|*|../|./|union|into|load_file|outfile/', $sql_str); if ($check) { echo '非法字符!!'; exit; } else { return $sql_str; } }
Copy after login

The usage method is as follows:

echo injCheck('1 or 1=1');
Copy after login

12. PHP page prompts and jumps

When we perform form operations, sometimes in order to be friendly If you need to prompt the user for the operation result and jump to the relevant page, please see the following function:

function message($msgTitle,$message,$jumpUrl){ $str = ''; $str .= ''; $str .= ''; $str .= ''; $str .= '页面提示'; $str .= ''; $str .= '
'; $str .= ''; $str .= '

'; $str .= '

'.$msgTitle.'

'; $str .= '

'; $str .= '

'.$message.'

'; $str .= '

系统将在 3 秒后自动跳转,如果不想等待,直接点击 这里 跳转

'; $str .= ""; $str .= '

'; $str .= '

'; $str .= ''; $str .= ''; echo $str; }
Copy after login

The usage is as follows:

message('操作提示','操作成功!','https://segmentfault.com/');
Copy after login

13. PHP calculation time

We are processing it time, it is necessary to calculate the length of time from the current time to a certain point in time. For example, to calculate the running time of the client, hh:mm:ss is usually used to represent

function changeTimeType($seconds) { if ($seconds > 3600) { $hours = intval($seconds / 3600); $minutes = $seconds % 3600; $time = $hours . ":" . gmstrftime('%M:%S', $minutes); } else { $time = gmstrftime('%H:%M:%S', $seconds); } return $time; }
Copy after login

The usage method is as follows:

$seconds = 3712; echo changeTimeType($seconds);
Copy after login

The following is Obtain client IP, string interception, download, etc. For details, please view the following code:

 1) { // 多字节字符 $return .= "%u" . strtoupper(bin2hex(mb_convert_encoding($str, 'UCS-2', $encoding))); } else { $return .= "%" . strtoupper(bin2hex($str)); } } return $return; }/** * php 实现 js unescape函数 * @param [type] $str [description] * @return [type] [description] */function unescape($str) { $str = rawurldecode($str); preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r); $ar = $r[0]; foreach($ar as $k=>$v) { if(substr($v,0,2) == "%u"){ $ar[$k] = iconv("UCS-2","utf-8//IGNORE",pack("H4",substr($v,-4))); } elseif(substr($v,0,3) == "") { $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1))); } elseif(substr($v,0,2) == "&#") { echo substr($v,2,-1).""; $ar[$k] = iconv("UCS-2","utf-8",pack("n",substr($v,2,-1))); } } return join("",$ar); }/** * 数字转人名币 * @param [type] $num [description] * @return [type] [description] */function num2rmb ($num) { $c1 = "零壹贰叁肆伍陆柒捌玖"; $c2 = "分角元拾佰仟万拾佰仟亿"; $num = round($num, 2); $num = $num * 100; if (strlen($num) > 10) { return "oh,sorry,the number is too long!"; } $i = 0; $c = ""; while (1) { if ($i == 0) { $n = substr($num, strlen($num)-1, 1); } else { $n = $num % 10; } $p1 = substr($c1, 3 * $n, 3); $p2 = substr($c2, 3 * $i, 3); if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) { $c = $p1 . $p2 . $c; } else { $c = $p1 . $c; } $i = $i + 1; $num = $num / 10; $num = (int)$num; if ($num == 0) { break; } } $j = 0; $slen = strlen($c); while ($j < $slen) { $m = substr($c, $j, 6); if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') { $left = substr($c, 0, $j); $right = substr($c, $j + 3); $c = $left . $right; $j = $j-3; $slen = $slen-3; } $j = $j + 3; } if (substr($c, strlen($c)-3, 3) == '零') { $c = substr($c, 0, strlen($c)-3); } // if there is a '0' on the end , chop it out return $c . "整"; }/** * 特殊的字符 * @param [type] $str [description] * @return [type] [description] */function makeSemiangle($str) { $arr = array( '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E', 'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J', 'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O', 'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T', 'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y', 'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd', 'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i', 'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n', 'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's', 't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x', 'y' => 'y', 'z' => 'z', '(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[', '】' => ']', '〖' => '[', '〗' => ']', '{' => '{', '}' => '}', '《' => '<', '》' => '>', '%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-', ':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.', ';' => ';', '?' => '?', '!' => '!', '…' => '-', '‖' => '|', '”' => '"', '“' => '"', ''' => '`', '‘' => '`', '|' => '|', '〃' => '"', ' ' => ' ','.' => '.'); return strtr($str, $arr); } /** * 下载 * @param [type] $filename [description] * @param string $dir [description] * @return [type] [description] */ function downloads($filename,$dir='./'){ $filepath = $dir.$filename; if (!file_exists($filepath)){ header("Content-type: text/html; charset=utf-8"); echo "File not found!"; exit; } else { $file = fopen($filepath,"r"); Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length: ".filesize($filepath)); Header("Content-Disposition: attachment; filename=".$filename); echo fread($file, filesize($filepath)); fclose($file); } } /** * 创建一个目录树 * @param [type] $dir [description] * @param integer $mode [description] * @return [type] [description] */ function mkdirs($dir, $mode = 0777) { if (!is_dir($dir)) { mkdirs(dirname($dir), $mode); return mkdir($dir, $mode); } return true; }
Copy after login

Related recommendations:

Summary of string operation functions in php

php delete folder operation function and several methods example code summary

php summary of commonly used string operation functions

The above is the detailed content of Sharing of commonly used PHP operation functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!