Home  >  Article  >  Backend Development  >  Summary of several very practical PHP function examples

Summary of several very practical PHP function examples

伊谢尔伦
伊谢尔伦Original
2017-06-27 11:42:291549browse

The examples in this article summarize some functions commonly used in PHP application development. These functions include character operations, file operations and other operations. They are shared with you for your reference. The details are as follows:

1. PHP encryption and decryption

PHP encryption and decryption functions can be used to encrypt some useful strings and store them in the database, and through Reversibly decrypts a string. This 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))), "12"); 
        return $decrypted; 
    }else{ 
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key)))); 
        return $encrypted; 
    } 
}

The usage method is as follows:

//以下是将字符串“Helloweba欢迎您”分别加密和解密 
//加密: 
echo encryptDecrypt('password', 'Helloweba欢迎您',0); 
//解密: 
echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);


2. PHP generates a random string

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

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

The usage method is as follows:

echo generateRandomString(20);


3, PHP Get the file extension (suffix)

The following function can quickly get the file extension or suffix.

function getExtension($filename){ 
  $myext = substr($filename, strrpos($filename, &#39;.&#39;)); 
  return str_replace(&#39;.&#39;,&#39;&#39;,$myext); 
}

The usage method is as follows:

$filename = &#39;我的文档.doc&#39;; 
echo getExtension($filename);


4. PHP gets the file size and formats it

The following functions can be used to get the file size size, and convert it into easy-to-read formats such as KB, MB, etc.

function formatSize($size) { 
    $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); 
    if ($size == 0) {  
        return(&#39;n/a&#39;);  
    } else { 
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);  
    } 
}

The usage method is as follows:

$thefile = filesize(&#39;test_file.mp3&#39;); 
echo formatSize($thefile);


5. PHP replaces tag characters

Sometimes we need to replace strings and templates To replace the tag with the specified content, you can use the following function:

function stringParser($string,$replacer){ 
    $result = str_replace(array_keys($replacer), array_values($replacer),$string); 
    return $result; 
}

The usage method is as follows:

$string = &#39;The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself&#39;; 
$replace_array = array(&#39;{b}&#39; => &#39;<b>&#39;,&#39;{/b}&#39; => &#39;</b>&#39;,&#39;{br}&#39; => &#39;<br />&#39;); 
echo stringParser($string,$replace_array);

6. PHP lists the file names in 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 />"; 
                } 
         } 
    } 
}

The usage is as follows:

listDirFiles(&#39;home/some_folder/&#39;);


7, PHP gets the current page URL

The following function can get the URL of the current page, whether it is http or https.

function curPageURL() { 
    $pageURL = &#39;http&#39;; 
    if (!empty($_SERVER[&#39;HTTPS&#39;])) {$pageURL .= "s";} 
    $pageURL .= "://"; 
    if ($_SERVER["SERVER_PORT"] != "80") { 
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; 
    } else { 
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; 
    } 
    return $pageURL; 
}

The usage method is as follows:

echo curPageURL();


8. PHP forces download of files

Sometimes we don’t want the browser to open the file directly, such as PDF file, but to download the file directly, then the following function can force the file to be downloaded. The application/octet-stream header type is used in the function.

function download($filename){ 
    if ((isset($filename))&&(file_exists($filename))){ 
       header("Content-length: ".filesize($filename)); 
       header(&#39;Content-Type: application/octet-stream&#39;); 
       header(&#39;Content-Disposition: attachment; filename="&#39; . $filename . &#39;"&#39;); 
       readfile("$filename"); 
    } else { 
       echo "Looks like file does not exist!"; 
    } 
}

Usage is as follows:

download(&#39;/down/test_45f73e852.zip&#39;);







The above is the detailed content of Summary of several very practical PHP function examples. For more information, please follow other related articles on the PHP Chinese website!

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