Very useful PHP functions to collect and organize

Source: Internet
Author: User
Tags decrypt md5 encryption

1, PHP encryption and decryption

PHP encryption and decryption functions can be used to encrypt some useful strings stored in the database, and by reversible decryption of the string, the function uses Base64 and MD5 encryption and decryption.

Cryptographic 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)));        return $decrypted;    } else{        $encrypted = Base64_encode (Mcrypt_encrypt (mcrypt_rijndael_256, MD5 ($key), $string, MCRYPT_MODE_CBC, MD5 ( MD5 ($key))));        return $encrypted;    }}

Here's how to encrypt and decrypt the string "Helloweba welcome You" separately

//加密: 
echo encryptDecrypt(‘password‘, ‘Helloweba欢迎您‘,0); 
//解密: 
echo encryptDecrypt(‘password‘, ‘z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=‘,1); 
2. PHP generates random string

The following functions are used when we need to generate a random name, a temporary password, and so on:

Generate random String function generaterandomstring ($length = ten) {    $characters = ' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ';    $randomString = ";    for ($i = 0; $i < $length; $i + +) {        $randomString. = $characters [rand (0, strlen ($characters)-1)];    }    return $randomString;}

echo generateRandomString(20); 
3. PHP Gets the file extension (suffix)

The following functions can quickly get the extension of a file as a suffix.

Gets the file name extension function getextension ($filename) {  $myext = substr ($filename, Strrpos ($filename, '. '));  Return Str_replace ('. ', ', $myext);}
$filename = ‘我的文档.doc‘; 
echo getExtension($filename); 
4, PHP get file size and format

The following functions can be used to obtain the size of the file and convert it into a readable format such as KB,MB.

Get file size and Format function formatsize ($size) {    $sizes = array ("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "Y B ");    if ($size = = 0) {return (' N/A '),} else {      return (round ($size/pow ($i = Floor (log ($size, 1024x768))), 2). $sizes [$ I]); }}

$thefile = filesize (' Test_file.mp3 ');

echo formatSize($thefile); 
5. PHP Replacement Label characters

Sometimes we need to replace the string and template tag with the specified content, and we can use the following function:

PHP Replacement Tag character function Stringparser ($string, $replacer) {    $result = Str_replace (Array_keys ($replacer), array_values ($replacer), $string);    return $result;}

$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> ',' {/b} ' = ' </b> ',' {br} ' = = ' <br/> ');

Echo Stringparser ($string,$replace_array);
6, PHP lists the file name under the directory

If you want to list all the files in the directory, use the following code:

Lists the files in the directory under Function Listdirfiles ($DirPath) {    if ($dir = Opendir ($DirPath)) {while         ($file = Readdir ($dir))!== False) {                if (!is_dir ($DirPath. $file))                {                    echo "filename: $file <br/>";                }    }}
listDirFiles(‘home/some_folder/‘); 
7. PHP Gets the current page URL

The following function can get the URL of the current page, whether HTTP or HTTPS.

Gets the current page of Urlfunction Curpageurl () {$pageURL = ' http ', if (!empty ($_server[' HTTPS '))) {$pageURL. = "S";} $pageURL. = "://", if ($_server["Server_port"]! = "n") {$pageURL. = $_server["SERVER_NAME"]. ":". $_server["Server_port" ].$_server["Request_uri"];} else {$pageURL. = $_server["SERVER_NAME"].$_server["Request_uri"];} return $pageURL;}

echo curPageURL(); 
8. PHP Force download file

Sometimes we do not want the browser to open the file directly, such as PDF file, but to download the file directly, then the following function can be forced to download the file, the function uses the Application/octet-stream header type.

force download 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!";    }}

download(‘/down/test_45f73e852.zip‘); 
9, PHP intercept string length

We often encounter the need to intercept the length of the string (including Chinese characters), such as the title display can not exceed the number of characters, the length of the ... Indicates that the following functions are available to meet your needs.

 /*&NBSP; 
 utf-8, gb2312 all support Chinese character interception function  
 cut_ STR (string,  intercept length,  start length,  encoding)  
  encoding defaults to  utf-8 
  Start length defaults to  0
/* Utf-8, gb2312 are supported by the Chinese character interception function Cut_str (string, intercept length, start length, encoding);  The encoding defaults to utf-8 start length by default 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 * *;        $sublen = $sublen;        $strlen = strlen ($string);        $tmpstr = "; for ($i =0; $i < $strlen; $i + +) {if ($i >= $start && $i < ($start + $sublen)) {if (Ord (subs                TR ($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; }}

 
$str = "jQuery插件实现的加载图片和页面效果"; 
echo cutStr($str,16); 
10. PHP Gets the client real IP

We often use the database to record the user's IP, the following code can obtain the client's real IP:

Get user Real ipfunction GetIP () {if (getenv ("Http_client_ip") && strcasecmp (getenv ("Http_client_ip"), "Unknown") $ip = getenv ("Http_client_ip"), ElseIf (getenv ("Http_x_forwarded_for") && strcasecmp (getenv ("Http_x_ Forwarded_for ")," Unknown ")) $ip = getenv (" http_x_forwarded_for "); ElseIf (getenv (" REMOTE_ADDR ") && strcasecmp (Getenv ("REMOTE_ADDR"), "Unknown")) $ip = getenv ("REMOTE_ADDR"), ElseIf (Isset ($_server[' remote_addr ')) && $_server[' remote_addr '] && STRCASECMP ($_server[' remote_addr '), "Unknown")) $ip = $_server[' remote_addr '];else$ip = "Unknown"; return ($IP);}
echo getIp(); 
11. PHP Prevents SQL injection

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

Prevent injection of function Injcheck ($sql _str) {$check = Preg_match ('/select|insert|update|delete|\ ' |\/\*|\*|\.\.\/|\.\/|union| into|load_file|outfile/', $sql _str), if ($check) {echo ' illegal characters!! '. $sql _str;exit;} else {return $sql _str;}}

echo injCheck(‘1 or 1=1‘); 
12. PHP page tips and jumps

When we are working on a form, sometimes in order to be friendly and prompt for user action results, and jump to the relevant page, see the following function:

Page Tip jump Function message ($msgTitle, $message, $jumpUrl) {$str = ' <! DOCTYPE html> '; $str. = ' 

message(‘操作提示‘,‘操作成功!‘,‘http://www.helloweba.com/‘); 
13. PHP Calculation length

When we process time, we need to calculate the current time distance from a point in time, such as calculating the client run time, usually expressed in hh:mm:ss.

Time-Length conversion 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;}

$seconds = 3712; 
echo changeTimeType($seconds);

Very useful PHP functions to collect

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.