Useful summary of common PHP functions

Source: Internet
Author: User
This article mainly introduces common PHP functions and summarizes examples and usage of functions such as encryption and decryption, string operations, file operations, and SQL injection, PHP project development is very useful. if you need it, you can refer to the examples in this article to summarize some functions that are often used in php application development. these functions have character operations, file operations and other operations are shared for your reference. The details are as follows:

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.

The code is 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 ($ key ))));
Return $ encrypted;
}
}


The usage is as follows:

The code is as follows:

// Encrypt and decrypt the string "Helloweba welcomes you"
// Encryption:
Echo encryptDecrypt ('password', 'Welcome to Helloweba ', 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:

The code is as follows:

Function generateRandomString ($ length = 10 ){
$ Characters = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy ';
$ RandomString = '';
For ($ I = 0; $ I <$ length; $ I ++ ){
$ RandomString. = $ characters [rand (0, strlen ($ characters)-1)];
}
Return $ randomString;
}


The usage is as follows:

The code 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.

The code is as follows:

Function getExtension ($ filename ){
$ Myext = substr ($ filename, strrpos ($ filename ,'.'));
Return str_replace ('.', '', $ myext );
}


The usage is as follows:

The code 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.

The code is as follows:

Function formatSize ($ size ){
$ Sizes = array ("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB ", "YB ");
If ($ size = 0 ){
Return ('n'/');
} Else {
Return (round ($ size/pow (1024, ($ I = floor (log ($ size, 1024), 2). $ sizes [$ I]);
}
}


The usage is as follows:

The code is as follows:

$ Thefile = filesize('test_file ');
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:

The code is as follows:

Function stringParser ($ string, $ replacer ){
$ Result = str_replace (array_keys ($ replacer), array_values ($ replacer), $ string );
Return $ result;
}


The usage is as follows:

The code 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:

The code is as follows:

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:

The code 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.

The code is 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;
}


The usage is as follows:

The code 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.

The code is 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! ";
}
}


The usage is as follows:

The code 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 is used... the following functions can meet your needs.

The code is as follows:

/*
Chinese character truncation functions supported by Utf-8 and gb2312
Cut_str (string, truncation length, start length, encoding );
The default encoding format is UTF-8.
The default start length 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) & gt; 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:

The code 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:

The code is as follows:

// Obtain the user's real IP address
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:

The code 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:

The code is as follows:

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:

The code 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:

The code 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 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:

The code is as follows:

Message ('Operation prompt ',' Operation successful! ', 'Http: // www.bitsCN.com /');


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.

The code is as follows:

Function changeTimeType ($ seconds ){
If ($ secondds> 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:

The code is as follows:

$ Seconds = 3712;
Echo changeTimeType ($ seconds );

I hope this article will help you with PHP programming.

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.