Home  >  Article  >  Backend Development  >  PHP functions (encryption and decryption, random strings, interception of string length, forced download, etc.)

PHP functions (encryption and decryption, random strings, interception of string length, forced download, etc.)

WBOY
WBOYOriginal
2016-07-25 08:51:331218browse
  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

Usage:

  1. //The following is to encrypt and decrypt the string "helloweba welcomes you" respectively
  2. //Encryption:
  3. echo encryptdecrypt('password', 'helloweba welcomes you',0);
  4. //Decryption:
  5. echo encryptdecrypt('password', 'z0jax4qmwcf+db5tnbp/xwdum84snrsxvvpxuaca4bk=',1);
Copy code

2. PHP generates random string

When you need to generate a random name, temporary password and other strings, use the following function:

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

Usage:

  1. echo generaterandomstring(20);
Copy code

3. PHP gets the file extension (suffix) Quickly get the file extension or 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 gets the file size and formats it Get the size of the file and convert it into kb, mb and other formats that are easy to read.

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

Usage:

  1. $thefile = filesize('test_file.mp3');
  2. echo formatsize($thefile);
Copy code

5. PHP replace tag characters Replace strings and template tags with 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}' => '< ;br />');

  3. echo stringparser($string,$replace_array);

Copy the code

6. PHP lists the directory file name List all files in a 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

How to use: listdirfiles('home/some_folder/');

7. Get the current page url with php The following function can get the url of the current page, whether it is 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 If you do not want the browser to directly open a file, such as a pdf file, but to download the file directly, the following function can force the file to be downloaded. The application/octet-stream header type is used in the function.

  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

Usage:

  1. download('/down/test_45f73e852.zip');
Copy code

9. PHP intercepts the string length When it is necessary to intercept the length of a string (including Chinese characters), such as how many characters cannot be exceeded in the title display, and the excess length is represented by..., the following function can meet your needs.

  1. /*

  2. Chinese character interception function supported by both utf-8 and gb2312
  3. cut_str(string, interception length, start length, encoding);
  4. The encoding defaults to utf-8
  5. Start length Default 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);< ;/p>
  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))>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 = "Loading images and page effects implemented by jquery plug-in";
  2. echo cutstr($str,16);
Copy code

10. Get the client’s real IP with php It is often necessary to use a database to record the user's IP and 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 prevents sql injection When querying the database, for security reasons, some illegal characters need to be filtered to prevent malicious SQL injection. Please 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 'Illegal character! ! ';
  5. exit;
  6. } else {
  7. return $sql_str;
  8. }
  9. }
Copy the code

The usage method 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 after 3 seconds Transfer, if you don’t want to wait, just click here Jump

    ';
  15. $str .= "<script>settimeout('location .replace('".$jumpurl."')',2000)</script>";
  16. $str .= '
';
  • $str .= '
  • ';
  • $str .= '';
  • $str .= '';
  • echo $str;
  • }
  • Copy code

    Usage:

    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

    Usage:

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


    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn