PHP加密和解密函数可以用来加密一些有用的字符串存放在数据库里,并且通过可逆解密字符串,该函数使用了base64和MD5加密和解密。
rush:
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(md5($key))));
return $encrypted;
}
}
使用方法如下:
//以下是将字符串“Helloweba欢迎您”分别加密和解密
//加密:
echo encryptDecrypt('password','jb51欢迎您',0);
//解密:
echo encryptDecrypt('password','z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);
当我们需要生成一个随机名字,临时密码等字符串时可以用到下面的函数:
rush:
PHP;">
function genera
terandomString($length = 10) {
$ch
aracters = '0123456789abcdefghijklm
nopqrstuvwxyzABCDEFGHIJKLM
nopQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $ch
aracters[rand(0,strlen($ch
aracters) - 1)];
}
return $randomString;
}
使用方法如下:
echo generaterandomString(20);
以下函数可以快速获取文件的扩展名即后缀。
rush:
PHP;">
function getExtension($filename){
$myext = substr($filename,strrpos($filename,'.'));
return str_replace('.','',$myext);
}
使用方法如下:
rush:
PHP;">
$filename = '我的文档.doc';
echo getExtension($filename);
以下使用的函数可以获取文件的大小,并且转换成便于阅读的KB,MB等格式。
rush:
PHP;">
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]);
}
}
使用方法如下:
rush:
PHP;">
$thefile = filesize('test_file.mp3');
echo formatSize($thefile);
有时我们需要将字符串、模板标签替换成指定的内容,可以用到下面的函数:
rush:
PHP;">
function stringParser($string,$replacer){
$result = str_replace(array_keys($replacer),array_values($replacer),$string);
return $result;
}
使用方法如下:
<div class="jb51code">
<pre class="brush:xhtml;">
$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);