PHP functions (encryption decryption, random string, intercept string length, forced download, etc.)

Source: Internet
Author: User
Tags decrypt
    1. function Encryptdecrypt ($key, $string, $decrypt) {
    2. if ($decrypt) {
    3. $decrypted = RTrim (Mcrypt_decrypt (mcrypt_rijndael_256, MD5 ($key), Base64_decode ($string), MCRYPT_MODE_CBC, MD5 (MD5 ($ Key)), "12");
    4. return $decrypted;
    5. }else{
    6. $encrypted = Base64_encode (Mcrypt_encrypt (mcrypt_rijndael_256, MD5 ($key), $string, MCRYPT_MODE_CBC, MD5 (MD5 ($KEY)))) ;
    7. return $encrypted;
    8. }
    9. }
Copy Code

How to use:

    1. Here's how to encrypt and decrypt the string "Helloweba welcome You" separately
    2. Encryption:
    3. echo encryptdecrypt (' Password ', ' Helloweba Welcome ', 0);
    4. Decrypt:
    5. echo encryptdecrypt (' Password ', ' z0jax4qmwcf+db5tnbp/xwdum84snrsxvvpxuaca4bk= ', 1);
Copy Code

2. PHP generates random string

Use the following function when you need to generate a string such as a random name, temporary password, and so on:

    1. function generaterandomstring ($length = 10) {
    2. $characters = ' 0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ';
    3. $randomstring = ";
    4. for ($i = 0; $i < $length; $i + +) {
    5. $randomstring. = $characters [rand (0, strlen ($characters)-1)];
    6. }
    7. return $randomstring;
    8. }
Copy Code

How to use:

    1. Echo generaterandomstring (20);
Copy Code

3, php get file extension (suffix) quick get file extension is the suffix.

    1. function GetExtension ($filename) {
    2. $myext = substr ($filename, Strrpos ($filename, '. '));
    3. Return Str_replace ('. ', ', $myext);
    4. }
Copy Code

How to use:

    1. $filename = ' My Documents. Doc ';
    2. echo getextension ($filename);
Copy Code

4, PHP to get the file size and format to get the size of the file, and converted into easy-to-read KB,MB and other formats.

    1. function Formatsize ($size) {
    2. $sizes = Array ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
    3. if ($size = = 0) {
    4. Return (' N/a ');
    5. } else {
    6. Return (Round ($size/pow ($i = Floor (log ($size, 1024x768))), 2). $sizes [$i]);
    7. }
    8. }
Copy Code

How to use:

    1. $thefile = filesize (' Test_file.mp3 ');
    2. echo formatsize ($thefile);
Copy Code

5. The PHP replacement tag character replaces the string, template tag with the specified content, function:

    1. function Stringparser ($string, $replacer) {
    2. $result = Str_replace (Array_keys ($replacer), Array_values ($replacer), $string);
    3. return $result;
    4. }
Copy Code

How to use:

    1. $string = ' The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself ';

    2. $replace _array = Array (' {b} ' = = ', ' {/b} '= ', ' {br} ' = ')
      ');

    3. Echo Stringparser ($string, $replace _array);

Copy Code

6. The file name under PHP list directory lists all the files in the directory:

    1. function Listdirfiles ($dirpath) {
    2. if ($dir = Opendir ($dirpath)) {
    3. while (($file = Readdir ($dir))!== false) {
    4. if (!is_dir ($dirpath. $file))
    5. {
    6. echo "FileName: $file
      ";
    7. }
    8. }
    9. }
    10. }
Copy Code

Method of Use: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.

    1. function Curpageurl () {
    2. $pageurl = ' http ';
    3. if (!empty ($_server[' https ')) {$pageurl. = "S";}
    4. $pageurl. = "://";
    5. if ($_server["Server_port"]! = "80") {
    6. $pageurl. = $_server["SERVER_NAME"]. ":". $_server["Server_port"].$_server["Request_uri"];
    7. } else {
    8. $pageurl. = $_server["SERVER_NAME"].$_server["Request_uri"];
    9. }
    10. return $pageurl;
    11. }
Copy Code

How to use:

    1. Echo Curpageurl ();
Copy Code

8, php force download file does not want to let the browser directly open files, such as PDF files, but to directly download files, then the following function can force download files, the function is used Application/octet-stream header type.

    1. function Download ($filename) {
    2. if ((Isset ($filename)) && (File_exists ($filename))) {
    3. Header ("Content-length:". FileSize ($filename));
    4. Header (' Content-type:application/octet-stream ');
    5. Header (' content-disposition:attachment; Filename= '. $filename. '"');
    6. ReadFile ("$filename");
    7. } else {
    8. echo "Looks like file does not exist!";
    9. }
    10. }
Copy Code

How to use:

    1. Download ('/down/test_45f73e852.zip ');
Copy Code

9, PHP intercept string length needs to intercept strings (including Chinese characters) length, 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.

  1. /*

  2. Chinese character interception function supported by Utf-8 and gb2312
  3. Cut_str (string, intercept length, start length, encode);
  4. encoding defaults to Utf-8
  5. Start length defaults to 0
  6. */
  7. function Cutstr ($string, $sublen, $start = 0, $code = ' utf-8 ') {
  8. if ($code = = ' Utf-8 ') {
  9. $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]/];
  10. Preg_match_all ($pa, $string, $t _string);

  11. if (count ($t _string[0])-$start > $sublen) return join ("', Array_slice ($t _string[0], $start, $sublen))." ...";

  12. return join ("', Array_slice ($t _string[0], $start, $sublen));
  13. }else{
  14. $start = $start;
  15. $sublen = $sublen;
  16. $strlen = strlen ($string);
  17. $tmpstr = ";

  18. for ($i =0; $i < $strlen; $i + +) {

  19. if ($i >= $start && $i < ($start + $sublen)) {
  20. if (Ord (substr ($string, $i, 1)) >129) {
  21. $tmpstr. = substr ($string, $i, 2);
  22. }else{
  23. $tmpstr. = substr ($string, $i, 1);
  24. }
  25. }
  26. if (Ord (substr ($string, $i, 1)) >129) $i + +;
  27. }
  28. if (strlen ($TMPSTR) < $strlen) $tmpstr. = "...";
  29. return $tmpstr;
  30. }
  31. }
Copy Code

How to use:

    1. $STR = "Load images and page effects implemented by jquery plug-ins";
    2. Echo Cutstr ($STR, 16);
Copy Code

10, PHP to obtain the client real IP often use the database to record the user's IP, to obtain the client's real IP:

    1. Get the user's real IP
    2. function GetIP () {
    3. if (getenv ("Http_client_ip") && strcasecmp (getenv ("Http_client_ip"), "Unknown")
    4. $ip = getenv ("Http_client_ip");
    5. Else
    6. if (getenv ("Http_x_forwarded_for") && strcasecmp (getenv ("Http_x_forwarded_for"), "Unknown")
    7. $ip = getenv ("Http_x_forwarded_for");
    8. Else
    9. if (getenv ("REMOTE_ADDR") && strcasecmp (getenv ("REMOTE_ADDR"), "Unknown")
    10. $ip = getenv ("REMOTE_ADDR");
    11. Else
    12. if (Isset ($_server[' remote_addr ')) && $_server[' remote_addr '] && strcasecmp ($_server[' remote_addr ') , "Unknown"))
    13. $ip = $_server[' remote_addr ');
    14. Else
    15. $ip = "Unknown";
    16. return ($IP);
    17. }
Copy Code

How to use:

    1. echo GetIP ();
Copy Code

11, PHP to prevent SQL injection when querying the database, for security reasons, you need to filter some illegal characters to prevent SQL malicious injection, please look at the function:

    1. function Injcheck ($sql _str) {
    2. $check = Preg_match ('/select|insert|update|delete|\ ' |\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql _str );
    3. if ($check) {
    4. echo ' Illegal characters!! ';
    5. Exit
    6. } else {
    7. return $sql _str;
    8. }
    9. }
Copy Code

Here's how to use it:

  1. Function message ($msgtitle, $message, $jumpurl) {
  2. $str = ";
  3. $str. = ';
  4. $str. = ';
  5. $str. = ' ;
  6. $str. = 'Page Tips';
  7. $str. = ' ;
  8. $str. = ';
  9. $str. = ';
  10. $str. = ';
  11. $str. = '

    '. $msgtitle. '

    ';
  12. $str. = ';
  13. $str. = '

    '. $message. '

    ';
  14. $str. = '

    The system will automatically jump after 3 seconds, if you do not want to wait, click here to jump

    ';
  15. $str. = "";
  16. $str. = ';
  17. $str. = ';
  18. $str. = ';
  19. $str. = ';
  20. Echo $str;
  21. }
Copy Code

How to use:

    1. function Changetimetype ($seconds) {
    2. if ($seconds > 3600) {
    3. $hours = intval ($seconds/3600);
    4. $minutes = $seconds% 3600;
    5. $time = $hours. ":" . Gmstrftime ('%m:%s ', $minutes);
    6. } else {
    7. $time = Gmstrftime ('%h:%m:%s ', $seconds);
    8. }
    9. return $time;
    10. }
Copy Code

How to use:

$seconds = 3712; echo Changetimetype ($seconds);
  • 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.