前端之家收集整理的这篇文章主要介绍了
13个PHP函数超实用,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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(md5($key))));
return $encrypted;
}
}
使用方法如下:
//以下是将字符串“Helloweba欢迎您”分别加密和解密
//加密:
echo encryptDecrypt('password','jb51欢迎您',0);
//解密:
echo encryptDecrypt('password','z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);
当我们需要生成一个随机名字,临时密码等字符串时可以用到下面的函数:
PHP;">
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);
以下函数可以快速获取文件的扩展名即后缀。
PHP;">
function getExtension($filename){
$myext = substr($filename,strrpos($filename,'.'));
return str_replace('.','',$myext);
}
使用方法如下:
PHP;">
$filename = '我的文档.doc';
echo getExtension($filename);
以下使用的函数可以获取文件的大小,并且转换成便于阅读的KB,MB等格式。
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]);
}
}
使用方法如下:
PHP;">
$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;
}
使用方法如下:
<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';
$replacearray = array('{b}' => '','{/b}' => '','{br}' => '@H403_61@');
echo stringParser($string,$replace_array);
PHP;">
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;
}
PHP;">
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!";
}
}