This article has compiled 13 PHP functions that are extremely practical. functions are a powerful source of PHP, but many PHP functions are not fully utilized, you must master the 13 PHP functions in this article.
1. PHP encryption and decryption
The PHP encryption and decryption function can be used to encrypt some useful strings and store them in the database. 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; } }
The usage is as follows:
// Encrypt and decrypt the string "Helloweba welcomes you"
// Encryption:
Echo encryptDecrypt ('Password', 'jb51 Welcome ', 0 );
// Decryption:
Echo encryptDecrypt ('Password', 'z0jax4qmwcf + db5TNbp/xwdUM84snRsXvvpXuaCa4Bk = ', 1 );
2. PHP generates random strings
The following functions can be used to generate a random name, temporary password, and other strings:
function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; }
The usage is as follows:
Echo generateRandomString (20 );
3. PHP obtains the file extension (suffix)
The following functions can quickly obtain the file extension, that is, the suffix.
function getExtension($filename){ $myext = substr($filename, strrpos($filename, '.')); return str_replace('.','',$myext); }
The usage is as follows:
$ Filename = 'my document .doc '; echo getExtension ($ filename );
4. PHP obtains and formats the file size.
The following functions can be used to obtain the file size and convert it to a readable format such as KB and MB.
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]); } }
The usage is as follows:
$thefile = filesize('test_file.mp3'); echo formatSize($thefile);
5. Replace tag characters in PHP
Sometimes we need to replace the string and template tag with the specified content. The following functions can be used:
function stringParser($string,$replacer){ $result = str_replace(array_keys($replacer), array_values($replacer),$string); return $result; }
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);
6. PHP lists the file names in the directory.
If you want to list all the files in the directory, use the following code:
function listDirFiles($DirPath){ if($dir = opendir($DirPath)){ while(($file = readdir($dir))!== false){ if(!is_dir($DirPath.$file)) { echo "filename: $file
"; } } } }
The usage is as follows:
listDirFiles('home/some_folder/');
7. PHP retrieves the URL of the current page
The following function obtains the URL of the current page, whether 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; }
The usage is as follows:
echo curPageURL();
8. Force download of PHP files
Sometimes we do not want the browser to open a file directly, such as a PDF file, but to download the file directly, the following function can force download the file, the function uses the application/octet-stream header type.
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!"; } }
The usage is as follows:
download('/down/test_45f73e852.zip');
9. PHP intercepts the string length
We often encounter the need to intercept the length of a string (including Chinese characters), for example, the title display cannot exceed how many characters, the length exceeds... The following functions can meet your needs.
/* Utf-8, gb2312 support Chinese Character truncation function cut_str (string, truncation length, start length, encoding ); the default encoding start length is UTF-8. The default value is 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 ;}}
The usage is as follows:
$ Str = "loading images and page effects implemented by jQuery plug-in"; echo cutStr ($ str, 16 );
10. PHP obtains the real IP address of the client.
We often use a database to record the user's IP address. The following code can obtain the real IP address of the client:
// Obtain the user's real 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 );}
The usage is as follows:
echo getIp();
11. PHP prevents SQL Injection
When querying the database, we need to filter out illegal characters for security reasons to prevent malicious SQL injection. Please refer to the function below:
Function injCheck ($ SQL _str) {$ check = preg_match ('/select | insert | update | delete | \' | \/\ * | \. \. \/| \. \/| union | into | load_file | outfile/', $ SQL _str); if ($ check) {echo 'invalid character !! '; Exit;} else {return $ SQL _str ;}}
The usage is as follows:
echo injCheck('1 or 1=1');
12. PHP page prompts and jumps
When we perform form operations, we sometimes prompt the user operation results for convenience and jump to the relevant page. Please refer to the following functions:
Function message ($ msgTitle, $ message, $ jumpUrl) {$ str =''; $ Str. =''; $ Str. =''; $ Str. ='
'; $ Str. ='Page prompt'; $ Str. =''; $ Str. =''; $ Str. =''; $ Str. =''; $ Str. = ''. $ msgTitle.''; $ str. ='
'; $ Str. = ''. $ message.''; $ str. ='
The system will automatically jump in 3 seconds. If you do not want to wait, click here to jump.
'; $ Str. = "script" setTimeout ('location. replace (\'". $ jumpUrl. "\ ')', 2000) script"; $ str. =''; $ Str. =''; $ Str. =''; $ Str. =''; Echo $ str ;}
The usage is as follows:
Message ('Operation prompt ',' operation successful! ', 'HTTP: // www.jb51.net ');
13. PHP computing duration
During processing time, we need to calculate the duration of the current time from a certain point in time. For example, the running duration of the computing client is usually indicated by hh: mm: ss.
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; }
The usage is as follows:
$seconds = 3712; echo changeTimeType($seconds);
The above is all the content in this article. Are these 13 php function codes wonderful? I hope they will be helpful for your learning.