PHP加密和解密函數能夠用來加密一些有用的字符串存放在數據庫裏,而且經過可逆解密字符串,該函數使用了base64和MD5加密和解密。php
//加密解密 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; } }
//如下是將字符串「Helloweba歡迎您」分別加密和解密 css
//加密:
echo encryptDecrypt('password', 'Helloweba歡迎您',0);
//解密:
echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);
當咱們須要生成一個隨機名字,臨時密碼等字符串時能夠用到下面的函數:html
//生成隨機字符串 function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; }
echo generateRandomString(20);
如下函數能夠快速獲取文件的擴展名即後綴。web
//獲取文件擴展名 function getExtension($filename){ $myext = substr($filename, strrpos($filename, '.')); return str_replace('.','',$myext); }
$filename = '個人文檔.doc';
echo getExtension($filename);
如下使用的函數能夠獲取文件的大小,而且轉換成便於閱讀的KB,MB等格式。sql
//獲取文件大小並格式化 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]); } }
$thefile = filesize('test_file.mp3'); 數據庫
echo formatSize($thefile);
有時咱們須要將字符串、模板標籤替換成指定的內容,能夠用到下面的函數:瀏覽器
//PHP替換標籤字符 function stringParser($string,$replacer){ $result = str_replace(array_keys($replacer), array_values($replacer),$string); return $result; }
$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>','{/b}' => '</b>','{br}' => '<br />');
echo stringParser($string,$replace_array);
若是你想列出目錄下的全部文件,使用如下代碼便可:安全
//列出目錄下的文件 function listDirFiles($DirPath){ if($dir = opendir($DirPath)){ while(($file = readdir($dir))!== false){ if(!is_dir($DirPath.$file)) { echo "filename: $file<br />"; } } } }
listDirFiles('home/some_folder/');
如下函數能夠獲取當前頁面的URL,無論是http仍是https。app
//獲取當前頁面的url 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; }
echo curPageURL();
有時咱們不想讓瀏覽器直接打開文件,如PDF文件,而是要直接下載文件,那麼如下函數能夠強制下載文件,函數中使用了application/octet-stream頭類型。dom
//強制下載 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!"; } }
download('/down/test_45f73e852.zip');
咱們常常會遇到須要截取字符串(含中文漢字)長度的狀況,好比標題顯示不能超過多少字符,超出的長度用...表示,如下函數能夠知足你的需求。
/*
Utf-八、gb2312都支持的漢字截取函數
cut_str(字符串, 截取長度, 開始長度, 編碼);
編碼默認爲 utf-8
開始長度默認爲 0
/* Utf-八、gb2312都支持的漢字截取函數 cut_str(字符串, 截取長度, 開始長度, 編碼); 編碼默認爲 utf-8 開始長度默認爲 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; } }
$str = "jQuery插件實現的加載圖片和頁面效果";
echo cutStr($str,16);
咱們常常要用數據庫記錄用戶的IP,如下代碼能夠獲取客戶端真實的IP:
//獲取用戶真實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); }
echo getIp();
咱們在查詢數據庫時,出於安全考慮,須要過濾一些非法字符防止SQL惡意注入,請看一下函數:
//防止注入 function injCheck($sql_str) { $check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str); if ($check) { echo '非法字符!!'.$sql_str; exit; } else { return $sql_str; } }
echo injCheck('1 or 1=1');
咱們在進行表單操做時,有時爲了友好須要提示用戶操做結果,並跳轉到相關頁面,請看如下函數:
//頁面提示跳轉 function message($msgTitle,$message,$jumpUrl){ $str = '<!DOCTYPE HTML>'; $str .= '<html>'; $str .= '<head>'; $str .= '<meta charset="utf-8">'; $str .= '<title>頁面提示</title>'; $str .= '<style type="text/css">'; $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; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; 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}'; $str .= '</style>'; $str .= '</head>'; $str .= '<body>'; $str .= '<div class="message">'; $str .= '<h3>'.$msgTitle.'</h3>'; $str .= '<div class="msg_txt">'; $str .= '<h4 class="red">'.$message.'</h4>'; $str .= '<p>系統將在 <span style="color:blue;font-weight:bold">3</span> 秒後自動跳轉,若是不想等待,直接點擊 <a href="{$jumpUrl}">這裏</a> 跳轉</p>'; $str .= "<script>setTimeout('location.replace(\'".$jumpUrl."\')',2000)</script>"; $str .= '</div>'; $str .= '</div>'; $str .= '</body>'; $str .= '</html>'; echo $str; }
message('操做提示','操做成功!','http://www.helloweba.com/');
咱們在處理時間時,須要計算當前時間距離某個時間點的時長,如計算客戶端運行時長,一般用hh:mm:ss表示。
//時間長度轉換 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; }
$seconds = 3712;
echo changeTimeType($seconds);
14.PHP生成UUID惟一序列
/** * Generates an UUID * * @author Anis uddin Ahmad * @param string an optional prefix * @return string the formatted uuid */ function uuid($prefix = '') { $chars = md5(uniqid(mt_rand(), true)); $uuid = substr($chars,0,8) . '-'; $uuid .= substr($chars,8,4) . '-'; $uuid .= substr($chars,12,4) . '-'; $uuid .= substr($chars,16,4) . '-'; $uuid .= substr($chars,20,12); return $prefix . $uuid; } //Example of using the function - //Using without prefix. echo uuid(); //Returns like ‘1225c695-cfb8-4ebb-aaaa-80da344e8352′ //Using with prefix echo uuid(‘urn:uuid:’);//Returns like ‘urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344e8352′