This article summarizes some of the functions commonly used in PHP application development, these functions have character operation, file operation and some other operations, share for everyone reference. Specifically as follows:
1, PHP encryption and decryption
PHP encryption and decryption functions can be used to encrypt some useful strings stored in the database, and through reversible decryption of strings, the function uses Base64 and MD5 encryption and decryption.
Copy Code code as follows:
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;
}
}
Use the following methods:
Copy Code code as follows:
The following is to encrypt and decrypt the string "Helloweba welcome" separately
Encryption:
echo encryptdecrypt (' Password ', ' Helloweba welcomes You ', 0);
Decrypt:
echo encryptdecrypt (' Password ', ' z0jax4qmwcf+db5tnbp/xwdum84snrsxvvpxuaca4bk= ', 1);
2. PHP generates random strings
The following function can be used when we need to generate a random name, a temporary password, etc string:
Copy Code code as follows:
function generaterandomstring ($length = 10) {
$characters = ' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ';
$randomString = ';
for ($i = 0; $i < $length; $i + +) {
$randomString. = $characters [rand (0, strlen ($characters)-1)];
}
return $randomString;
}
Use the following methods:
Copy Code code as follows:
Echo generaterandomstring (20);
3, php get file extension (suffix)
The following function can quickly get the extension of the file, which is the suffix.
Copy Code code as follows:
function GetExtension ($filename) {
$myext = substr ($filename, Strrpos ($filename, '. '));
Return Str_replace ('. ', ', $myext);
}
Use the following methods:
Copy Code code as follows:
$filename = ' My Documents. Doc ';
echo getextension ($filename);
4, PHP get file size and format
The following functions are used to get the size of the file and convert it into a KB,MB format that is easy to read.
Copy Code code as follows:
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]);
}
}
Use the following methods:
Copy Code code as follows:
$thefile = filesize (' Test_file.mp3 ');
echo formatsize ($thefile);
5, PHP replacement label characters
Sometimes we need to replace the string, template tag with the specified content, we can use the following function:
Copy Code code as follows:
function Stringparser ($string, $replacer) {
$result = Str_replace (Array_keys ($replacer), Array_values ($replacer), $string);
return $result;
}
Use the following methods:
Copy Code code as follows:
$string = ' The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to ' link {describe ';
$replace _array = Array (' {b} ' => ' <b> ', ' {//} ' => ' </b> ', ' {br} ' => ' <br/> ');
Echo Stringparser ($string, $replace _array);
6, PHP listed directory under the file name
If you want to list all the files in the directory, use the following code:
Copy Code code as follows:
function Listdirfiles ($DirPath) {
if ($dir = Opendir ($DirPath)) {
while (($file = Readdir ($dir))!== false) {
if (!is_dir ($DirPath. $file))
{
echo "FileName: $file <br/>";
}
}
}
}
Use the following methods:
Copy Code code as follows:
Listdirfiles (' home/some_folder/');
7, PHP get the current page URL
The following function gets the URL of the current page, whether HTTP or HTTPS.
Copy Code code as follows:
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;
}
Use the following methods:
Copy Code code as follows:
8, php forced download files
Sometimes we do not want the browser to open files directly, such as PDF file, but to download files directly, then the following function can force the download file, the function uses the Application/octet-stream header type.
Copy Code code as follows:
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!";
}
}
Use the following methods:
Copy Code code as follows:
Download ('/down/test_45f73e852.zip ');
9, PHP intercept string length
We often encounter the need to intercept the string (including Chinese characters) of the length of the case, such as the title display can not exceed the number of characters, the length of the above ... Indicates that the following functions can meet your needs.
Copy Code code as follows:
/*
Chinese character interception function supported by Utf-8 and gb2312
Cut_str (string, intercept length, start length, coding);
encoding defaults to Utf-8
Start length defaults to 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;
}
}
Use the following methods:
Copy Code code as follows:
$STR = "The Load picture and page effect implemented by jquery plugin";
Echo Cutstr ($STR, 16);
10, PHP access to real IP client
We often use the database to record the user's IP, the following code can obtain the client's true IP:
Copy Code code as follows:
Get user 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);
}
Use the following methods:
Copy Code code as follows:
11, PHP to prevent SQL injection
We are querying the database, for security reasons, we need to filter some illegal characters to prevent SQL malicious injection, please look at the function:
Copy Code code as follows:
function Injcheck ($sql _str) {
$check = Preg_match ('/select|insert|update|delete| ' | /*|*|.. /|. /|union|into|load_file|outfile/', $sql _str);
if ($check) {
echo ' Illegal character!! ';
Exit
} else {
return $sql _str;
}
}
Use the following methods:
Copy Code code as follows:
Echo Injcheck (' 1 or 1=1 ');
12, php page prompts and jump
When we are doing a form operation, sometimes in order to be friendly need to prompt the user action results, and jump to the relevant page, see the following function:
Copy Code code as follows:
Function message ($msgTitle, $message, $JUMPURL) {
$str = ' <! DOCTYPE html> ';
$str. = ' <html> ';
$str. = ' <head> ';
$str. = ' <meta charset= ' utf-8 ' > ';
$str. = ' <title> page tips </title> ';
$str. = ' <style type= ' text/css ' > ';
$str. = ' *{margin:0; Padding:0}a{color: #369; text-decoration:none;} a:hover{text-decoration:underline}body{height:100% font:12px/18px Tahoma, Arial, sans-serif; color: #424242; Background: #fff}.message{width:450px; height:120px margin:16% auto; border:1px solid #99b1c4; background: #ecf7fb}. Message h3{height:28px; line-height:28px background: #2c91c6; text-align:center; color: #fff; font-size:14px}.msg_txt {padding:10px; Margin-top:8px}.msg_txt h4{line-height:26px font-size:14px}.msg_txt h4.red{color: #f30}.msg_txt p{ LINE-HEIGHT:22PX} ';
$str. = ' </style> ';
$str. = ' </head> ';
$str. = ' <body> ';
$str. = ' <div class= ' message ' > ';
$str. = ' <h3> '. $msgTitle. ' </h3> ';
$str. = ' <div class= ' msg_txt ' > ';
$str. = ' <h4 class= ' red ' > '. $message. ' </h4> ';
$str. = ' <p> system will automatically jump after <span style= "Color:blue;font-weight:bold" >3</span> seconds, if you do not want to wait, directly click <a href= " {$JUMPURL} "> here </a> jump </p>";
$str. = "<script>settimeout (' Location.replace (') $jumpUrl." ') ' </script> ';
$str. = ' </div> ';
$str. = ' </div> ';
$str. = ' </body> ';
$str. = ' </html> ';
Echo $str;
}
Use the following methods:
Copy Code code as follows:
Message (' Operation Prompt ', ' Operation successful! ', ' http://www.jb51.net/');
13, the length of the PHP calculation
When we process time, we need to calculate the current time distance from a point in time, such as the calculation of client run time, usually in Hh:mm:ss.
Copy Code code as follows:
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;
}
Use the following methods:
Copy Code code as follows:
$seconds = 3712;
echo Changetimetype ($seconds);
I hope this article will help you with your PHP program design.
Here are some extra materials for everyone to enjoy:
This article summarizes common PHP functions, including obtaining client IP, string interception, downloading, and more, see the following code:
<?php/** * Get client IP * @return [string] [description]/function Getclientip () {$ip = NULL;
if (Isset ($_server[' http_x_forwarded_for ')) {$arr = explode (', ', $_server[' http_x_forwarded_for ']);
$pos = Array_search (' unknown ', $arr);
if (false!== $pos) unset ($arr [$pos]);
$ip = Trim ($arr [0]);
}elseif (Isset ($_server[' http_client_ip ')) {$ip = $_server[' http_client_ip '];
}elseif (Isset ($_server[' remote_addr ')) {$ip = $_server[' remote_addr ']; }//IP address legal authentication $ip = (False!== Ip2long ($IP))?
$ip: ' 0.0.0.0 ';
return $IP;
/** * Get online IP * @return String/function Getonlineip ($format =0) {global $S _global; if (Empty ($S _global[' Onlineip ')) {if (getenv (' http_client_ip ') && strcasecmp (getenv (' http_client_ip '), '
Unknown ') {$onlineip = getenv (' http_client_ip '); } elseif (getenv (' http_x_forwarded_for ') && strcasecmp (getenv (' http_x_forwarded_for '), ' unknown ')) {$
Onlineip = getenv (' http_x_forwarded_for '); } elseif (getenv (' REMOTE_ADDR ') && strcasecmp (getenv (' remote_addr '), ' unknown ')) {$onlineip = getenv (' remote_addr '); } elseif (Isset ($_server[' remote_addr ')) && $_server[' remote_addr '] && strcasecmp ($_server[' Remote_
ADDR '], ' unknown ') {$onlineip = $_server[' remote_addr ']; } preg_match ("/[\d\.]
{7,15}/", $onlineip, $onlineipmatches); $S _global[' onlineip '] = $onlineipmatches [0]?
$onlineipmatches [0]: ' Unknown ';
} if ($format) {$ips = explode ('. ', $S _global[' Onlineip '));
For ($i =0 $i <3; $i + +) {$ips [$i] = Intval ($ips [$i]);
return sprintf ('%03d%03d%03d ', $ips [0], $ips [1], $ips [2]);
else {return $S _global[' Onlineip '];
/** * Get URL * @return [type] [description]/function GetUrl () {$pageURL = ' http ';
if (Isset ($_server["https")) && $_server["https"] = = "on") {$pageURL. = "S";
$pageURL. = "://"; if ($_server["Server_port"]!= "O") {$pageURL. = $_server["Http_host"]. ":" . $_server["Server_port"].
$_server["Request_uri"]; } else{$pageURL. = $_server["Http_host"]. $_server["Request_uri"];
return $pageURL; /** * Gets the access path root of the current site * @return [type] [description]/function Getsiteurl () {$uri = $_server[' Request_uri ']?$_ser
ver[' Request_uri ']:($_server[' php_self ']?$_server[' php_self ']:$_server[' script_name ']);
Return ' http://' $_server[' http_host '].substr ($uri, 0, Strrpos ($uri, '/') +1); /** * String intercept, support Chinese and other encoding * @param [string] $str [strings] * @param integer $start [starting position] * @param integer $length [intercept length ] * @param string $charset [string encoding] * @param boolean $suffix [whether there is an ellipsis] * @return [type] [description]/function msub STR ($STR, $start =0, $length =15, $charset = "Utf-8", $suffix =true) {if (Function_exists ("Mb_substr")) {return Mb_substr ($
STR, $start, $length, $charset);
} elseif (Function_exists (' iconv_substr ')) {return iconv_substr ($str, $start, $length, $charset); } $re [' utf-8 '] = '/[\x01-\x7f]| [\XC2-\XDF] [\x80-\xbf]| [\xe0-\xef] [\X80-\XBF] {2}| [\xf0-\xff] [\X80-\XBF]
{3}/"; $re [' gb2312 '] = "/[\x01-\x7f]| [\xb0-\xf7]
[\xa0-\xfe]/]; $re [' gbk '] = "/[\x01-\x7f]| [\x81-\xfe]
[\x40-\xfe]/]; $re [' big5 '] = "/[\x01-\x7f]| [\x81-\xfe] ([\x40-\x7e]|\xa1-\xfe])
/";
Preg_match_all ($re [$charset], $STR, $match);
$slice = Join ("", Array_slice ($match [0], $start, $length)); if ($suffix) {return $slice. "
...";
return $slice; /** * PHP Implementation js escape function * @param [type] $string [description] * @param string $encoding [description] * @return [t
YPE] [description]/function Escape ($string, $encoding = ' UTF-8 ') {$return = null;
for ($x = 0; $x < Mb_strlen ($string, $encoding); $x + +) {$str = Mb_substr ($string, $x, 1, $encoding); if (strlen ($STR) > 1) {//multibyte character $return. = "%u". Strtoupper (Bin2Hex (mb_convert_encoding ($str, ' UCS-2 ', $encoding))
;
else {$return. = "%". Strtoupper (Bin2Hex ($STR));
} return $return; /** * PHP Implementation js unescape function * @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);} /** * Digital coin * @param [Type] $num [description] * @return [type] [description]/function NUM2RMB ($num) {$c 1 = zero
One of the three establishments Woolu Qi Ba Nine ";
$c 2 = "cent of the points of the hundred million thousand thousand million";
$num = Round ($num, 2);
$num = $num * 100;
if (strlen ($num) > Ten) {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;
$p 1 = substr ($c 1, 3 * $n, 3);
$p 2 = substr ($c 2, 3 * $i, 3); if ($n!= ' 0 ' | | ($n = = ' 0 ' && ($p 2 = ' billion ' | | $p 2 = ' million' ||
$p 2 = = ' Yuan ')) {$c = $p 1. $p 2. $c;
else {$c = $p 1. $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 = = ' 0 ' | | $m = ' 0 ' | | $m = ' 0 ' | | $m = = ' 00 ') {$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) = = ' 0 ') {$c = substr ($c, 0, strlen ($c)-3); }//If there is a ' 0 ' on the "end", chop it out return $c.
"Whole"; /** * Special character * @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 ', ' (' => ' (', ') ' => ') ', ' (' => ' [', ' ' => '] ', ' ' => ' [', ' ', ' ' => '] ', ' => ' [', ' ' => '] ', ' {' => ' {', '} ' => '} ', ' ' => ' < ', ' ' => ' > ', '% ' => '% ', ' + ' => ' + ', '-' => '-', '-' => '-', ' ' => '-', ': ' => ': ', ' '。 ' => '. ', ', ' => ', ', ', ' => '. ', ', ' => ', ', ', ' and ' => '; ' => '? ', '! ' => '! ', ' ... ' => '-', ' ‖ ' => ' | ', ' ' => ', ' ' ' => ' ', ' ' => ', ', ' ' => ', ' ' | ' => ' | ', ' ' => ', ', ' => ', '.
' => '. ');
Return Strtr ($str, $arr); /** * Download * @param [type] $filename [description] * @param string $dir [description] * @return [type] [descriptio
N] */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); }/** * Create a directory tree * @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; }