PHP常用工具方法集,更新时间 2018-7-14
加密,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}' => '','{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"; } } }}//7.获取当前页面URLfunction 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.获取客户端真实IPfunction 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);}//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 = ''; $str .= ''; $str .= ''; $str .= ' '; $str .= '页面提示 '; $str .= ''; $str .= ''; $str .= ''; $str .= ''; $str .= ''; $str .= ''; $str .= ''; 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('/].+)>/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" "; 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);}'.$msgTitle.'
'; $str .= ''; $str .= ''; $str .= ''.$message.'
'; $str .= '系统将在 3 秒后自动跳转,如果不想等待,直接点击 这里 跳转
'; $str .= " "; $str .= '
持续更新中...