Php functions (encryption and decryption, random string, truncated string length, forced download, etc)

Source: Internet
Author: User
Php functions (encryption and decryption, random string, truncated string length, forced download, etc)

  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 ($ key ))));
  7. Return $ encrypted;
  8. }
  9. }

Usage:

  1. // Encrypt and decrypt the string "helloweba welcomes you"
  2. // Encryption:
  3. Echo encryptdecrypt ('password', 'Welcome to helloweba ', 0 );
  4. // Decryption:
  5. Echo encryptdecrypt ('password', 'z0jax4qmwcf + db5tnbp/xwdum84snrsxvvpxuaca4bk = ', 1 );

2. php generates random strings

Use the following function to generate a random name, temporary password, and other strings:

  1. Function generaterandomstring ($ length = 10 ){
  2. $ Characters = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy ';
  3. $ Randomstring = '';
  4. For ($ I = 0; $ I <$ length; $ I ++ ){
  5. $ Randomstring. = $ characters [rand (0, strlen ($ characters)-1)];
  6. }
  7. Return $ randomstring;
  8. }

Usage:

  1. Echo generaterandomstring (20 );

3. php obtains the file extension (suffix)Quickly obtain the file extension, that is, the suffix.

  1. Function getextension ($ filename ){
  2. $ Myext = substr ($ filename, strrpos ($ filename ,'.'));
  3. Return str_replace ('.', '', $ myext );
  4. }

Usage:

  1. $ Filename = 'My document .doc ';
  2. Echo getextension ($ filename );

4. php obtains and formats the file size.Obtain the file size and convert it to a readable format such as kb and mb.

  1. Function formatsize ($ size ){
  2. $ Sizes = array ("bytes", "kb", "mb", "gb", "tb", "pb", "eb", "zb ", "yb ");
  3. If ($ size = 0 ){
  4. Return ('n'/');
  5. } Else {
  6. Return (round ($ size/pow (1024, ($ I = floor (log ($ size, 1024), 2). $ sizes [$ I]);
  7. }
  8. }

Usage:

  1. $ Thefile = filesize('test_file ');
  2. Echo formatsize ($ thefile );

5. replace tag characters in phpReplace the string and 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. }

Usage:

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

6. php lists the file names in the directory.List all 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. }

Usage:Listdirfiles ('Home/some_folder /');

7. php retrieves the url of the current pageThe following function obtains 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. }

Usage:

  1. Echo curpageurl ();

8. force download of php filesIf you do not want the browser to open a file directly, such as a PDF file, but download the file directly, the following functions can force download the file. the function uses the 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. }

Usage:

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

9. php intercepts the string lengthWhen the length of a string (including Chinese characters) needs to be intercepted, for example, the title cannot contain more than many characters, and the length exceeds the length... The following functions can meet your needs.

  1. /*

  2. Chinese character truncation functions supported by UTF-8 and gb2312
  3. Cut_str (string, truncation length, start length, encoding );
  4. The default encoding format is UTF-8.
  5. The default start length is 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 * 2;
  15. $ Sublen = $ sublen * 2;
  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) & gt; 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. }

Usage:

  1. $ Str = "loading images and Page effects implemented by jquery plug-in ";
  2. Echo cutstr ($ str, 16 );

10. php obtains the real ip address of the client.You often need to use a database to record the user's ip address and obtain the real ip address of the client:

  1. // Obtain the user's real ip address
  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. }

Usage:

  1. Echo getip ();

11. php prevents SQL injectionWhen querying a database, for security reasons, you need to filter out invalid characters to prevent malicious SQL injection. Take a 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 'invalid character !! ';
  5. Exit;
  6. } Else {
  7. Return $ SQL _str;
  8. }
  9. }

The usage is as follows:

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

    ';

  11. $ Str. = ''. $ msgtitle .'';
  12. $ Str. ='

    ';

  13. $ Str. = ''. $ message .'';
  14. $ Str. ='

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

    ';
  15. $ Str. = "script settimeout ('location. replace (\ '". $ jumpurl. "\') ', 2000) script";
  16. $ Str. ='

    ';
  17. $ Str. ='

    ';
  18. $ Str. ='';
  19. $ Str. ='';
  20. Echo $ str;
  21. }

Usage:

  1. Function changetimetype ($ seconds ){
  2. If ($ secondds> 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. }

Usage:

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