13 PHP Functions Super Practical _javascript Tips

Source: Internet
Author: User
Tags decrypt md5 md5 encryption ord sql injection

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.

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)), "a"); 
    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 following is to encrypt and decrypt the string "Helloweba welcome" separately
echo encryptdecrypt (' Password ', ' jb51 welcomes You ', 0);
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:

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

Use the following methods:

Echo generaterandomstring (20);

3, php get file extension (suffix)

The following function can quickly get the extension of the file, which is the suffix.

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

Use the following methods:

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

function Formatsize ($size) { 
  $sizes = array ("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"); 
  if ($size = = 0) {return 
    (' N/a '); 
  } else {return 
   ($size/pow (1024, ($i = Floor (log ($size, 1024))) (round), 2). $sizes [$i]); 

Use the following methods:

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

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

Use the following methods:

$string = ' The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to ' link {describe '; 
$replace _array = Array (' {b} ' => ' <b> ', ' {//} ' => ' </b> ', ' {br} ' => ' <br/> '); 
Echo Stringparser ($string, $replace _array);

6, PHP listed directory under the file name

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/> "; 

Use the following methods:

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.

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

Use the following methods:

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.

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:

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.

/* Utf-8, gb2312 are supported by the Chinese character intercept function 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] 

    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:

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

Gets the user real IP 
function GetIP () { 
  if (getenv ("Http_client_ip") && strcasecmp (getenv ("Http_client_ip"), " Unknown ") 
    $ip = getenv (" Http_client_ip "); 
    if (getenv ("Http_x_forwarded_for") && strcasecmp (getenv ("Http_x_forwarded_for"), "Unknown" 
      ) $ip = getenv ("http_x_forwarded_for"); 
      if (getenv ("REMOTE_ADDR") && strcasecmp (getenv ("REMOTE_ADDR"), "Unknown") 
        $ip = getenv ("REMOTE _addr "); 
        if (isset ($_server[' remote_addr ')) && $_server[' remote_addr '] && strcasecmp ($_server[' Remote_addr '], "unknown") 
          $ip = $_server[' remote_addr ']; 
          $ip = "Unknown"; 
  return ($IP); 

Use the following methods:

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:

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

Use the following methods:

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:

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

Use the following methods:

Message (' Operation Prompt ', ' Operation successful! ', ' http://www.jb51.net ');
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.

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:

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

The above is the entire content of this article, these 13 PHP function code is not very exciting, I hope to help you learn.

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.