-
- 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 code
Usage:
-
- //The following is to encrypt and decrypt the string "helloweba welcomes you" respectively
- //Encryption:
- echo encryptdecrypt('password', 'helloweba welcomes you',0);
- //Decryption:
- echo encryptdecrypt('password', 'z0jax4qmwcf+db5tnbp/xwdum84snrsxvvpxuaca4bk=',1);
Copy code
2. PHP generates random string
When you need to generate a random name, temporary password and other strings, use the following function:
-
- function generaterandomstring($length = 10) {
- $characters = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz';
- $randomstring = '';
- for ($i = 0; < $length; $i++) {
- $randomstring .= $characters[rand(0, strlen($characters) - 1)];
- }
- return $randomstring;
- }
Copy code Usage:
- echo generaterandomstring(20);
Copy code3. PHP gets the file extension (suffix)
Quickly get the file extension or suffix.
- function getextension($filename){
- $myext = substr($filename, strrpos($filename, '.'));
- return str_replace('.','',$myext);
- }
Copy codeHow to use:
- $filename = 'My Documents.doc';
- echo getextension($filename);
Copy code4. PHP gets the file size and formats it
Get the size of the file and convert it into kb, mb and other formats that are easy to read.
- 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 codeUsage:
- $thefile = filesize('test_file.mp3');
- echo formatsize($thefile);
Copy code5. PHP replace tag characters
Replace strings and template tags with specified content, function:
- function stringparser($string,$replacer){
- $result = str_replace(array_keys($replacer), array_values($replacer),$string);
- return $result;
- }
Copy code How to use:
$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}' => '< ;br />');
echo stringparser($string,$replace_array);
-
Copy the code
6. PHP lists the directory file name
List all files in a directory:
-
- function listdirfiles($dirpath){
- if($dir = opendir($dirpath)){
- while(($file = readdir($dir))!== false){
- if(!is_dir ($dirpath.$file))
- {
- echo "filename: $file
";
- }
- }
- }
- }
-
Copy code
How to use:
listdirfiles('home/some_folder/');
7. Get the current page url with php
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 code
How to use :
8. PHP force download file
If you do not want the browser to directly open a file, such as a pdf file, but to download the file directly, 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 code
Usage:
-
- download('/down/test_45f73e852.zip');
Copy code
9. PHP intercepts the string length
When it is necessary to intercept the length of a string (including Chinese characters), such as how many characters cannot be exceeded in the title display, and the excess length is represented by..., the following function can meet your needs.
-
-
/*
- Chinese character interception function supported by both utf-8 and gb2312
- cut_str(string, interception length, start length, encoding);
- The encoding defaults to utf-8
- Start length Default 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);< ;/p>
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 code
How to use :
-
- $str = "Loading images and page effects implemented by jquery plug-in";
- echo cutstr($str,16);
Copy code
10. Get the client’s real IP with php
It is often necessary to use a database to record the user's IP and obtain the client's real IP:
-
- //Get 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);
- }
-
Copy code
How to use:
11. PHP prevents sql injection
When querying the database, for security reasons, some illegal characters need to be filtered to prevent malicious SQL 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 'Illegal character! ! ';
- exit;
- } else {
- return $sql_str;
- }
- }
-
Copy the code
The usage method is as follows:
-
- 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 after 3 seconds Transfer, if you don’t want to wait, just click here Jump ';
- $str .= "<script>settimeout('location .replace('".$jumpurl."')',2000)</script>";
- $str .= '
';
- $str .= '
';
- $str .= '';
- $str .= '';
- echo $str;
- }
-
Copy code
Usage:
-
- 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 code
Usage:
$seconds = 3712;
echo changetimetype($seconds); |