超實用PHP函數總結整理

一、PHP加密解密

PHP加密和解密函數能夠用來加密一些有用的字符串存放在數據庫裏,而且經過可逆解密字符串,該函數使用了base64和MD5加密和解密css

 1 function encryptDecrypt($key, $string, $decrypt){ 
 2 
 3     if($decrypt){ 
 4 
 5         $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode
 6        ($string), MCRYPT_MODE_CBC, md5(md5($key))), "12"); 
 7 
 8         return $decrypted; 
 9 
10     }else{ 
11 
12         $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key),
13        $string, MCRYPT_MODE_CBC, md5(md5($key)))); 
14 
15         return $encrypted; 
16 
17     } 
18 
19 }

使用方法以下:html

1 //如下是將字符串「Helloweba歡迎您」分別加密和解密 
2 
3 //加密: 
4 
5 echo encryptDecrypt('password', 'Helloweba歡迎您',0); 
6 
7 //解密: 
8 
9 echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);

二、PHP生成隨機字符串

       當咱們須要生成一個隨機名字,臨時密碼等字符串時能夠用到下面的函數:web

 1 function generateRandomString($length = 10) { 
 2 
 3     $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
 4 
 5     $randomString = ''; 
 6 
 7     for ($i = 0; $i < $length; $i++) { 
 8 
 9         $randomString .= $characters[rand(0, strlen($characters) - 1)]; 
10 
11     } 
12 
13     return $randomString; 
14 
15 }

  使用方法以下:sql

1 echo generateRandomString(20);

三、PHP獲取文件擴展名(後綴)

 如下函數能夠快速獲取文件的擴展名即後綴。數據庫

1 function getExtension($filename){ 
2 
3   $myext = substr($filename, strrpos($filename, '.')); 
4 
5   return str_replace('.','',$myext); 
6 
7 }

使用方法以下:瀏覽器

1 $filename = '個人文檔.doc'; 
2 
3 echo getExtension($filename);

四、PHP獲取文件大小並格式化

如下使用的函數能夠獲取文件的大小,而且轉換成便於閱讀的KB,MB等格式。安全

 1 function formatSize($size) { 
 2 
 3     $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); 
 4 
 5     if ($size == 0) {  
 6 
 7         return('n/a');  
 8 
 9     } else { 
10 
11       return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);  
12 
13     } 
14 
15 }

使用方法以下:app

1 $thefile = filesize('test_file.mp3'); 
2 
3 echo formatSize($thefile);

五、PHP替換標籤字符

有時咱們須要將字符串、模板標籤替換成指定的內容,能夠用到下面的函數:dom

 1 function stringParser($string,$replacer){ 
 2 
 3     $result = str_replace(array_keys($replacer), array_values($replacer),$string); 
 4 
 5     return $result; 
 6 
 7 }
 8 
 9 //使用方法以下
10 
11 $string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used 
12 {br}to describe the link {br}itself'; 
13 
14 $replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '<br >'); 
15 
16  
17 
18 echo stringParser($string,$replace_array);</br >

六、PHP列出目錄下的文件名

若是你想列出目錄下的全部文件,使用如下代碼便可:函數

 1 function listDirFiles($DirPath){ 
 2 
 3     if($dir = opendir($DirPath)){ 
 4 
 5          while(($file = readdir($dir))!== false){ 
 6 
 7                 if(!is_dir($DirPath.$file)) 
 8 
 9                 { 
10 
11                     echo "filename: $file<br >"; 
12 
13                 } 
14 
15          } 
16 
17     } 
18 
19 }
20 
21 //使用方法以下
22 
23 listDirFiles('home/some_folder/');

七、PHP獲取當前頁面URL

如下函數能夠獲取當前頁面的URL,無論是http仍是https。

 1 function curPageURL() { 
 2 
 3     $pageURL = 'http'; 
 4 
 5     if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";} 
 6 
 7     $pageURL .= "://"; 
 8 
 9     if ($_SERVER["SERVER_PORT"] != "80") { 
10 
11         $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER
12 ["REQUEST_URI"]; 
13 
14     } else { 
15 
16         $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; 
17 
18     } 
19 
20     return $pageURL; 
21 
22 }
23 
24 //使用方法以下
25 
26 echo curPageURL();

八、PHP強制下載文件

有時咱們不想讓瀏覽器直接打開文件,如PDF文件,而是要直接下載文件,那麼如下函數能夠強制下載文件,函數中使用了application/octet-stream頭類型。

 1 function download($filename){ 
 2 
 3     if ((isset($filename))&&(file_exists($filename))){ 
 4 
 5        header("Content-length: ".filesize($filename)); 
 6 
 7        header('Content-Type: application/octet-stream'); 
 8 
 9        header('Content-Disposition: attachment; filename="' . $filename . '"'); 
10 
11        readfile("$filename"); 
12 
13     } else { 
14 
15        echo "Looks like file does not exist!"; 
16 
17     } 
18 
19 }
20 
21 //使用方法以下
22 
23 download('/down/test_45f73e852.zip'); 

九、PHP截取字符串長度

咱們常常會遇到須要截取字符串(含中文漢字)長度的狀況,好比標題顯示不能超過多少字符,超出的長度用…表示,如下函數能夠知足你的需求。

 1 /* 
 2 
 3  Utf-八、gb2312都支持的漢字截取函數 
 4 
 5  cut_str(字符串, 截取長度, 開始長度, 編碼); 
 6 
 7  編碼默認爲 utf-8 
 8 
 9  開始長度默認爲 0 
10 
11 */ 
12 
13 function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){ 
14 
15     if($code == 'UTF-8'){ 
16 
17         $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]/"; 
18 
19         preg_match_all($pa, $string, $t_string); 
20 
21  
22 
23         if(count($t_string[0]) - $start > $sublen) return join('', array_slice
24 ($t_string[0], $start, $sublen))."..."; 
25 
26         return join('', array_slice($t_string[0], $start, $sublen)); 
27 
28     }else{ 
29 
30         $start = $start*2; 
31 
32         $sublen = $sublen*2; 
33 
34         $strlen = strlen($string); 
35 
36         $tmpstr = ''; 
37 
38  
39 
40         for($i=0; $i<$strlen; $i++){ 
41 
42             if($i>=$start && $i<($start+$sublen)){ 
43 
44                 if(ord(substr($string, $i, 1))>129){ 
45 
46                     $tmpstr.= substr($string, $i, 2); 
47 
48                 }else{ 
49 
50                     $tmpstr.= substr($string, $i, 1); 
51 
52                 } 
53 
54             } 
55 
56             if(ord(substr($string, $i, 1))>129) $i++; 
57 
58         } 
59 
60         if(strlen($tmpstr)<$strlen ) $tmpstr.= "..."; 
61 
62         return $tmpstr; 
63 
64     } 
65 
66 }
67 
68 //使用方法以下
69 
70 $str = "jQuery插件實現的加載圖片和頁面效果"; 
71 
72 echo cutStr($str,16);

十、PHP獲取客戶端真實IP

咱們常常要用數據庫記錄用戶的IP,如下代碼能夠獲取客戶端真實的IP:

 1 //獲取用戶真實IP 
 2 
 3 function getIp() { 
 4 
 5     if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"),
 6  "unknown")) 
 7 
 8         $ip = getenv("HTTP_CLIENT_IP"); 
 9 
10     else 
11 
12         if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) 
13 
14             $ip = getenv("HTTP_X_FORWARDED_FOR"); 
15 
16         else 
17 
18             if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
19 
20                 $ip = getenv("REMOTE_ADDR"); 
21 
22             else 
23 
24                 if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && 
25 strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
26 
27                     $ip = $_SERVER['REMOTE_ADDR']; 
28 
29                 else 
30 
31                     $ip = "unknown"; 
32 
33     return ($ip); 
34 
35 }
36 
37 //使用方法以下
38 
39 echo getIp();

十一、PHP防止SQL注入

咱們在查詢數據庫時,出於安全考慮,須要過濾一些非法字符防止SQL惡意注入,請看一下函數:

 1 function injCheck($sql_str) {  
 2 
 3     $check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into
 4 |load_file|outfile/', $sql_str); 
 5 
 6     if ($check) { 
 7 
 8         echo '非法字符!!'; 
 9 
10         exit; 
11 
12     } else { 
13 
14         return $sql_str; 
15 
16     } 
17 
18 }
19 
20 //使用方法以下
21 
22 echo injCheck('1 or 1=1');

十二、PHP頁面提示與跳轉

咱們在進行表單操做時,有時爲了友好須要提示用戶操做結果,並跳轉到相關頁面,請看如下函數:

 1 function message($msgTitle,$message,$jumpUrl){ 
 2     $str = '<!DOCTYPE HTML>'; 
 3     $str .= '<html>'; 
 4     $str .= '<head>'; 
 5     $str .= '<meta charset="utf-8">'; 
 6     $str .= '<title>頁面提示</title>'; 
 7     $str .= '<style type="text/css">'; 
 8     $str .= '*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:12px/18px Tahoma, Arial,  sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; 
 9 margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; 
10 line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}'; 
11     $str .= '</style>'; 
12     $str .= '</head>'; 
13     $str .= '<body>'; 
14     $str .= '<div>'; 
15     $str .= '<h3>'.$msgTitle.'</h3>'; 
16     $str .= '<div>'; 
17     $str .= '<h4>'.$message.'</h4>'; 
18     $str .= '<p>系統將在 <span style="color:blue;font-weight:bold">3</span> 秒後自動跳轉,若是不想等待,直接點擊 <a href="{$jumpUrl}">這裏</a> 跳轉</p>'; 
19     $str .= "<script>setTimeout('location.replace(\'".$jumpUrl."\')',2000)</script>"; 
20     $str .= '</div>'; 
21     $str .= '</div>'; 
22     $str .= '</body>'; 
23     $str .= '</html>'; 
24     echo $str; 
25 }
26 
27 //使用方法以下 
28 
29 message('操做提示','操做成功!','http://www.helloweba.com/');

1三、PHP計算時長

咱們在處理時間時,須要計算當前時間距離某個時間點的時長,如計算客戶端運行時長,一般用hh:mm:ss表示。

 1 function changeTimeType($seconds) { 
 2 
 3     if ($seconds > 3600) { 
 4 
 5         $hours = intval($seconds / 3600); 
 6 
 7         $minutes = $seconds % 3600; 
 8 
 9         $time = $hours . ":" . gmstrftime('%M:%S', $minutes); 
10 
11     } else { 
12 
13         $time = gmstrftime('%H:%M:%S', $seconds); 
14 
15     } 
16 
17     return $time; 
18 
19 }
20 
21 //使用方法以下
22 
23 $seconds = 3712; 
24 
25 echo changeTimeType($seconds);
相關文章
相關標籤/搜索