Home  >  Article  >  Backend Development  >  Very practical summary of common PHP functions, very practical PHP summary_PHP tutorial

Very practical summary of common PHP functions, very practical PHP summary_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:11:27845browse

A very practical summary of common PHP functions, a very practical PHP summary

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 stored in the database, and reversibly decrypt the strings. This function uses base64 and MD5 encryption and decryption.

Copy code The code is as follows:
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;
}
}

How to use:
Copy code The code is as follows:
//The following is to encrypt and decrypt the string "Helloweba welcomes you" respectively
//Encryption:
echo encryptDecrypt('password', 'Helloweba welcomes you',0);
//Decrypt:
echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);

2. PHP generates random strings

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

Copy code The code is as follows:
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
Return $randomString;
}

How to use:
Copy code The code is as follows:
echo generateRandomString(20);

3. PHP gets the file extension (suffix)

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

Copy code The code is as follows:
function getExtension($filename){
$myext = substr($filename, strrpos($filename, '.'));
Return str_replace('.','',$myext);
}

How to use:
Copy code The code is as follows:
$filename = 'My Documents.doc';
echo getExtension($filename);

4. PHP gets the file size and formats it

The function used below can get the size of the file and convert it into easy-to-read KB, MB and other formats.

Copy code The code is as follows:
function formatSize($size) {
$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
If ($size == 0) {
         return('n/a');
} else {
Return (round($size/pow(1024, ($i = floor(log($size, 1024))))), 2) . $sizes[$i]);
}
}

How to use:
Copy code The code is as follows:
$thefile = filesize('test_file.mp3');
echo formatSize($thefile);

5. PHP replaces tag characters

Sometimes we need to replace strings and template tags with specified content. You can use the following function:

Copy code The code is as follows:
function stringParser($string,$replacer){
$result = str_replace(array_keys($replacer), array_values($replacer),$string);
Return $result;
}

How to use:
Copy code The code is as follows:
$string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself';
$replace_array = array('{b}' => '','{/b}' => '','{br}' => '
');

echo stringParser($string,$replace_array);

6. PHP lists the file names in the directory

If you want to list all files in a directory, use the following code:

Copy code The code is as follows:
function listDirFiles($DirPath){
If($dir = opendir($DirPath)){
​​​​​while(($file = readdir($dir))!== false){
If(!is_dir($DirPath.$file))
                                                                            echo "filename: $file
";
                                                                                                                 }
}
}

How to use:


Copy code The code is as follows:listDirFiles('home/some_folder/');
7. PHP gets the current page URL
The following function can get the URL of the current page, whether it is http or https.


Copy code The code is as follows:function curPageURL() {
$pageURL = 'http';
If (!empty($_SERVER['HTTPS'])) {$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;
}

How to use:


Copy code The code is as follows:echo curPageURL();
8. PHP forces file download
Sometimes we don’t want the browser to directly open a file, such as a 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.


Copy code The code is as follows: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!";
}
}

How to use:


Copy code The code is as follows:download('/down/test_45f73e852.zip');
9. PHP intercepts string length
We often encounter situations where we need to intercept the length of a string (including Chinese characters). For example, the title cannot display more than a few characters, and the excess length is represented by.... The following function can meet your needs.


Copy code The code is as follows:
/*
Chinese character interception function supported by Utf-8 and gb2312
cut_str(string, cut length, start length, encoding);
The encoding defaults to utf-8
The default starting length is 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][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;
}
}
How to use:

Copy code The code is as follows:
$str = "Loading images and page effects implemented by jQuery plug-in";
echo cutStr($str,16);

10. PHP gets the real IP of the client

We often use a database to record the user’s IP. The following code can obtain the client’s real IP:


Copy the code The code is as follows:
//Get the user’s real IP
function getIp() {
If (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
          $ip = getenv("HTTP_CLIENT_IP");
else
If (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
                $ip = getenv("HTTP_X_FORWARDED_FOR");
        else
If (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                     $ip = getenv("REMOTE_ADDR");
              else
If (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
                    else
                        $ip = "unknown";
Return ($ip);
}
How to use:

Copy code The code is as follows:
echo getIp();

11. PHP prevents SQL injection

When we query the database, for security reasons, we need to filter some illegal characters to prevent malicious SQL injection. Please take a look at the function:

Copy code The code is as follows:
function injCheck($sql_str) {
$check = preg_match('/select|insert|update|delete|'|/*|*|../|./|union|into|load_file|outfile/', $sql_str);
If ($check) {
echo 'Illegal character! ! ';
exit;
} else {
          return $sql_str;
}
}

How to use:
Copy code The code is as follows:
echo injCheck('1 or 1=1');

12. PHP page prompts and jumps

When we perform form operations, sometimes we need to prompt the user for the operation results and jump to the relevant page for the sake of friendliness. Please see the following function:

Copy code The code is as follows:
function message($msgTitle,$message,$jumpUrl){
$str = '';
$str .= '';
$str .= '';
$str .= '';
$str .= 'Page prompt';
$str .= '';
$str .= '';
$str .= '';
$str .= '
';
$str .= '

'.$msgTitle.'

';
$str .= '
';
$str .= '

'.$message.'

';
$str .= '

The system will automatically jump after 3 seconds. If you don't want to wait, just clickHere Jump

';
$str .= "<script>setTimeout('location.replace('".$jumpUrl."')',2000)</script>";
$str .= '
';
$str .= '
';
$str .= '';
$str .= '';
echo $str;
}

How to use:
Copy code The code is as follows:
message('Operation prompt','Operation successful!','http://www.bkjia.com/ ');

13. PHP calculation time

When we process time, we need to calculate the length of time from the current time to a certain point in time. For example, when calculating the running time of the client, it is usually expressed by hh:mm:ss.

Copy code The code is as follows:
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;
}

How to use:
Copy code The code is as follows:
$seconds = 3712;
echo changeTimeType($seconds);

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/929098.htmlTechArticleA very practical summary of common PHP functions, a very practical PHP summary. The examples in this article summarize some commonly used functions in PHP application development. Functions, these functions include character operations, file operations and other...
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