PHP常用工具方法集,更新时间 2018-7-14
<?php
/*** 常用工具方法集* Author: zj*//**
工具总述
1.加密解密
2.生成随机字符串
3.获取文件扩展名(后缀)
4.文件大小格式化
5.替换标签字符
6.列出目录下的文件名
7.获取当前页面URL
8.让浏览器强制下载文件
9.字符串显示长度,超出使用...显示
10.获取客户端真实IP
11.防止SQL注入,判断是否有非法字符
12.页面提示与跳转
13.计算时长
14.写入日志文件
16.过滤特殊字符的函数 utf-8可用
17.统计文章字数和图片数
18.封装页面跳转函数
19.获取当前文件路径
20.获取当前文件目录
21.获取当前时间字符串
22.获取时间戳格式化时间字符串*///1.加密解密,$decrypt:0->加密,1->解密
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;}
}//2.生成随机字符串
function generateRandomString($length = 10) {$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';$randomString = '';for ($i = 0; $i < $length; $i++) {$randomString .= $characters[rand(0, strlen($characters) - 1)];}return $randomString;
}//3.获取文件扩展名(后缀)
function getExtension($filename){$myext = substr($filename, strrpos($filename, '.')); //strrpos:最后位置return str_replace('.','',$myext);
}//4.文件大小格式化
function formatSize($size) {$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");if ($size == 0) {return('n/a');} else {//log(x,base):指定了可选的参数 base,log() 返回 logbasex ,否则 log() 返回参数 x 的自然对数;//pow(x,y):返回 x 的 y 次方的幂,如x=4,y=2,结果为16//重点获取$i:1024*1024*1024...级别对数return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);}
}//5.替换标签字符
/* 使用方法
$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 stringParser($string, $replacer){//str_replace对应替换多个字符$result = str_replace(array_keys($replacer), array_values($replacer), $string);return $result;
}//6.列出目录下的文件名,不列出文件夹名
function listDirFiles($DirPath){if($dir = opendir($DirPath)){while(($file = readdir($dir)) !== false){if(!is_dir($DirPath.$file)){echo "filename: $file<br />";}}}
}//7.获取当前页面URL
function curPageURLhost() {$pageURL = 'http';if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";}$pageURL .= "://"; //拼接if ($_SERVER["SERVER_PORT"] != "80") {$pageURL .= $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];} else {$pageURL .= $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];}return $pageURL;
}//7-2.获取当前页面URL目录
function curPageURLaddrCatalog() {$pageURL = curPageURLhost();return $pageURL=substr($pageURL,0, strrpos($pageURL, '/')+1);
}//8.让浏览器强制下载文件-原文件名
function download($filepath){if ((isset($filepath))&&(file_exists($filepath))){header("Content-length: ".filesize($filepath));header('Content-Type: application/octet-stream');header('Content-Disposition: attachment; filename="' . substr($filepath,strrpos($filepath, '/')+1, strlen($filepath)) . '"');readfile("$filepath");} else {echo "文件不存在!";}
}//8.让浏览器强制下载文件-文件重命名
function downloadScel($filepath, $filename){if ((isset($filepath))&&(file_exists($filepath))){header("Content-length: ".filesize($filepath));header('Content-Type: application/octet-stream');header('Content-Disposition: attachment; filename="' . $filename.'.'.getExtension($filepath) . '"');readfile("$filepath");} else {echo "文件不存在!";}
}//9.字符串显示长度,超出使用...显示
/*Utf-8、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;}
}//10.获取客户端真实IP
function getIp() {if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))$ip = getenv("HTTP_CLIENT_IP");elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))$ip = getenv("HTTP_X_FORWARDED_FOR");elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))$ip = getenv("REMOTE_ADDR");elseif (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))$ip = $_SERVER['REMOTE_ADDR'];else$ip = "unknown";return ($ip);
}//11.防止SQL注入,判断是否有非法字符
function injCheck($sql_str) {$check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);if ($check) {echo '非法字符!!';exit;} else {return $sql_str;}
}//12.页面提示与跳转
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:14px/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>';$str .= '<h3>'.$msgTitle.'</h3>';$str .= '<div>';$str .= '<h4>'.$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;
}//13.计算时长
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;
}/*** 14.写入日志文件* @parm1 : 日志文件名称* @parm2 : 记录的信息*/
function logFile($filename, $msg){$str = "[".date("Y-m-d H:i:s",time())."] ".$msg . PHP_EOL;file_put_contents($filename, $str,FILE_APPEND);
}//16.过滤特殊字符的函数 utf-8可用,过滤例如'&'中的'amp;'
function filterSpechars ($string){return preg_replace('/[\x00-\x1F\x7F-\x9F]/u', '', $string);
}/*** 17.统计文章字数和图片数* 参数:文章内容字符串* 返回:array*/
function countWords($str){$str = trim($str);$pattern = "/\[#img_[0-9]+_[a-z]*_[0-9]+_[a-zA-Z]*/i";#统计图片数preg_match_all($pattern, $str, $match_arrs);$picCount = count($match_arrs[0]);##增加新的图片记数方式preg_match_all('/<img /i',$str,$match_arrs);$picCount = $picCount + count($match_arrs[0]);#统计字数$str = preg_replace($pattern, "", $str);$str = preg_replace("/<img([^>].+)>/iU","", $str); ##去掉图片标签$str = str_replace(' ','', $str); ##去掉空格$wordCount = mb_strwidth(trim(strip_tags($str)));return array('wordCount'=>$wordCount,'picCount'=>$picCount,);
}/** 18.封装页面跳转函数* @param $url 目标地址* @param $info 提示信息* @param $sec 等待时间* return void
*/
function jump($url,$info=null,$sec=3)
{if(is_null($info)){header("Location:$url");}else{// header("Refersh:$sec;URL=$url");echo"<meta http-equiv=\"refresh\" content=".$sec.";URL=".$url.">";echo $info;}die(); //结束当前脚本运行
}/** 19.获取当前文件路径* return path
*/
function getThisPath()
{return __FILE__;
}/** 20.获取当前文件目录* 等价方法:getcwd();* return path
*/
function getThisCatalog()
{return __DIR__.'\\';
}/** 21.获取当前时间字符串* @param 可选参数,格式化* return date
*/
function getNowDateTime($format='Y-m-d H:i:s')
{return date($format);
}/** 22.获取时间戳格式化时间字符串* @param 时间戳* @param 可选参数,格式化* return date
*/
function getFormatDateTime($timestamp, $format='Y-m-d H:i:s')
{return date($format, $timestamp);
}
持续更新中...