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.
The code is as follows |
Copy Code |
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:
/
The code is as follows |
Copy Code |
/The following is to encrypt and decrypt the string "Helloweba welcome" separately
Encryption:
echo encryptdecrypt (' Password ', ' Helloweba welcomes You ', 0); |
Decrypt:
The code is as follows |
Copy Code |
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:
The code is as follows |
Copy Code |
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:
The code is as follows |
Copy Code |
Echo generaterandomstring (20); |
3, php get file extension (suffix)
The following function can quickly get the extension of the file, which is the suffix.
The code is as follows |
Copy Code |
function GetExtension ($filename) {
$myext = substr ($filename, Strrpos ($filename, '. '));
Return Str_replace ('. ', ', $myext);
} |
Use the following methods:
The code is as follows |
Copy Code |
$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.
The code is as follows |
Copy Code |
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:
The code is as follows |
Copy Code |
$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:
The code is as follows |
Copy Code |
function Stringparser ($string, $replacer) {
$result = Str_replace (Array_keys ($replacer), Array_values ($replacer), $string);
return $result;
} |
Use the following methods
The code is as follows |
Copy Code |
$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> ', ' {/n} ' => ' </b> ', ' {br} ' => ' <br > ');
Echo Stringparser ($string, $replace _array); </br > |
6, PHP listed directory under the file name
If you want to list all the files in the directory, use the following code:
The code is as follows |
Copy Code |
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
The code is as follows |
Copy Code |
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.
The code is as follows |
Copy Code |
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
The code is as follows |
Copy Code |
Echo Curpageurl (); |
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.
code is as follows |
copy code |
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
The code is as follows |
Copy Code |
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.
The code is as follows |
Copy Code |
/*
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
The code is as follows |
Copy Code |
$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:
/
The code is as follows |
Copy Code |
/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
The code is as follows |
Copy Code |
echo GetIP (); |
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:
The code is as follows |
Copy Code |
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
The code is as follows |
Copy Code |
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:
The code is as follows |
Copy Code |
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> ';
$str. = ' <h3> '. $msgTitle. ' </h3> ';
$str. = ' <div> ';
$str. = ' <h4> '. $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
The code is as follows |
Copy Code |
Message (' Operation Prompt ', ' Operation successful! ', ' http://www.helloweba.com/'); |
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.
code is as follows |
copy code |
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
The code is as follows |
Copy Code |
$seconds = 3712;
echo Changetimetype ($seconds); |