Summary and collation of super-practical PHP functions

Source: Internet
Author: User
Tags ord

Summary and collation of super-practical PHP functions

2014-12-06 Category: Web development, programming development, home essence of the No comment Source: Moonlight Light Blog

share to: more 81, 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.

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 use it:

The following is the string "Helloweba welcome you" separately encrypted and decrypted//encrypted: Echo encryptdecrypt (' Password ', ' Helloweba Welcome ', 0); Decryption: 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:

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

Here's how to use it:

Echo generaterandomstring (20);
3. PHP Gets the file extension (suffix)

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

function GetExtension ($filename) {   $myext = substr ($filename, Strrpos ($filename, '. '));   Return Str_replace ('. ', ', $myext); }

Here's how to use it:

$filename = ' My Documents. 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.

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 ($i = Floor (log ($size, 1024))), 2). $sizes [$i]);      } }

Here's how to use it:

$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:

function Stringparser ($string, $replacer) {     $result = Str_replace (Array_keys ($replacer), Array_values ($replacer) , $string);     return $result; }

Here's how to use it:

$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:

function Listdirfiles ($DirPath) {     if ($dir = Opendir ($DirPath)) {while          (($file = Readdir ($dir))!== false) {                 if (!is_dir ($DirPath. $file))                 {                     echo "filename: $file <br/>";                 }          }     }

Here's how to use it:

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.

function Curpageurl () {     $pageURL = ' http ';     if (!empty ($_server[' HTTPS ')) {$pageURL. = "S";}     $pageURL. = "://";     if ($_server["Server_port"]! = "+") {         $pageURL. = $_server["SERVER_NAME"]. ":". $_server["Server_port"].$_server ["Request_uri"];     } else {         $pageURL. = $_server["SERVER_NAME"].$_server["Request_uri"];     }     return $pageURL; }

Here's how to use it:

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.

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

Here's how to use it:

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.

/* 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 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 (su                 BSTR ($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; } }

Here's how to use it:

$STR = "Load images and page effects implemented by jquery plug-ins"; 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 the 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); }

Here's how to use it:

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:

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

Here's how to use it:

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:

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

Here's how to use it:

Message (' Operation Tip ', ' Operation successful! ', ' 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.

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; }

Here's how to use it:

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

Summary and collation of super-practical PHP functions

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.