1、根据生日算年龄
public static function calcAge($birthday){
$age=0;
if (!empty($birthday)) {
if($age === false){
return 0;
}
//explode()函数:把字符串打散为数组 2019-8-2 打散为 2019 8 2
//list() 函数用于在一次操作中给一组变量赋值 $y1=2019 $m1=8 $d1=2
list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
list($y2, $m2, $d2) = explode("-", date("Y-m-d"), time());
$age = $y2 - $y1;
if ((int) ($m2 . $d2) < (int) ($m1 . $d1)) {
$age -= 1;
}
}
return $age;
}
2、验证码
public static function Is_password($value, $minLen = 5, $maxLen = 16) {
$match = '/^[\\~!@#$%^&*()-_=+|{}\[\],.?\/:;\'\"\d\w]{' . $minLen . ',' . $maxLen . '}$/';
//trim() 函数移除字符串两侧的空白字符或其他预定义字符
$v = trim($value);
if (empty($v)) {
return false;
} else {
//preg_match()函数搜索字符串模式,如果模式存在返回true,否则返回false
return preg_match($match, $v);
}
}
3. 验证手机
public static function Is_mobile($value, $match = '/^[(86)|0]?(13\d{9})|(15\d{9})|(18\d{9})$/') {
$v = trim($value);
if (empty($v))
return false;
return preg_match($match, $v);
}
4、验证座机
public static function Is_telephone($value, $match = '/^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$/') {
$v = trim($value);
if (empty($v))
return false;
return preg_match($match, $v);
}
5、 时间格式判断处理方法
public static function Is_time($timeStr) {
if (empty($timeStr))
return false;
$match = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/s';
return preg_match($match, $timeStr);
}
6、查找img标签处理方法
public static function exist_img($img) {
if (empty($img))
return false;
$match = '/]+>/is';
return preg_match($match, $img);
}
7、判断数字处理方法
public static function Is_number($number, $start = 1, $limit = NULL) {
if (empty($number))
return false;
$match = '/^\d{' . $start . ',' . $limit . '}$/is';
return preg_match($match, $number);
}
8、判断是否为正确邮箱地址
public static function Is_email($email) {
return preg_match("/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/", $email);
}
9、判断url处理方法
public static function Is_Url($url) {
if (empty($url))
return false;
$match = '/www.[a-zA-z0-9]+.[a-zA-z0-9]+/is';
return preg_match($match, $url);
}
10、生成公共的TOKEN方法 @param unknown $data 要加密的数据 @return string 返回加密结果
public static function create_token($data) {
//生成全局加密KEY mt_rand() 使用 Mersenne Twister 算法返回随机整数
$token_key_1 = mt_rand(10000000, 99999999); //前8位KEY
$token_key_2 = mt_rand(10000000, 99999999); //后8位KEY
if (empty($_SESSION['TOKEN_KEY_1'])) {
$_SESSION['TOKEN_KEY_1'] = $token_key_1;
}
if (empty($_SESSION['TOKEN_KEY_2'])) {
$_SESSION['TOKEN_KEY_2'] = $token_key_2;
}
return md5($_SESSION['TOKEN_KEY_1'] . $data . $_SESSION['TOKEN_KEY_2']);
11、下载文件处理方法
public static function download($path, $fileName, $downName = '') {
$path = trim($path);
$fileName = trim($fileName);
//文件名转码 iconv()转码函数
$fileName = iconv('utf-8', 'gb2312', $fileName);
//设置路径 strlen()函数返回字符串的长度: substr() 函数返回字符串的一部分
if (substr($path, strlen($path) - 1, strlen($path)) != '/') {
$file = $_SERVER['DOCUMENT_ROOT'] . $path . '/' . $fileName;
} else {
$file = $_SERVER['DOCUMENT_ROOT'] . $path . $fileName;
}
//die($file);
file_exists($file) || die('下载文件不存在');
$file_size = filesize($file);
//读取文件
$fp = fopen($file, "r");
$buffer_size = 1024;
$cur_pos = 0;
$downName = empty($downName) ? $fileName : $downName;
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: $file_size");
header("Content-Disposition: attachment; filename=" . $downName);
//刷出缓冲区
ob_clean();
flush();
//输出文件
while (!feof($fp) && $file_size - $cur_pos > $buffer_size) {
$buffer = fread($fp, $buffer_size);
echo $buffer;
$cur_pos += $buffer_size;
}
$buffer = fread($fp, $file_size - $cur_pos);
echo $buffer;
fclose($fp);
return true;
}
12、图片上传处理方法
public static function uploadFile($path, $fileName, $typeArr = '', $upConfig = '') {
//上传文件类型列表
empty($typeArr) && $typeArr = array(
'image/jpg',
'image/jpeg',
'image/png',
'image/pjpeg',
'image/gif',
'image/bmp',
'image/x-png'
);
$path = substr($path, 0, 1) == '/' ? $_SERVER["DOCUMENT_ROOT"] . $path : $_SERVER["DOCUMENT_ROOT"] . '/' . $path; //重组上传路径
// die($path);
empty($upConfig['max_file_size']) && $upConfig['max_file_size'] = 2000000; //上传文件大小限制, 单位BYTE
//$destination_folder = $path; //上传文件路径
empty($upConfig['watermark']) && $upConfig['watermark'] = 0; //是否附加水印(1为加水印,其他为不加水印);
empty($upConfig['watertype']) && $upConfig['watertype'] = 1; //水印类型(1为文字,2为图片)
empty($upConfig['waterposition']) && $upConfig['waterposition'] = 1; //水印位置(1为左下角,2为右下角,3为左上角,4为右上角,5为居中);
//$waterstring="http://www.xplore.cn/"; //水印字符串
//$waterimg="xplore.gif"; //水印图片
//$imgpreview=1; //是否生成预览图(1为生成,其他为不生成);
$imgpreviewsize = 1 / 2; //缩略图比例
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!is_uploaded_file($_FILES[$fileName]['tmp_name'])) {
//是否存在文件
$msg_data['status'] = 0;
$msg_data['info'] = '上传文件不存在';
return $msg_data;
}
$file = $_FILES[$fileName];
if ($upConfig['max_file_size'] < $file["size"]) {
//检查文件大小
$msg_data['status'] = 0;
$msg_data['info'] = '上传文件过大';
return $msg_data;
}
if (!in_array($file["type"], $typeArr)) {
//检查文件类型
$msg_data['status'] = 0;
$msg_data['info'] = '上传文件类型不符';
return $msg_data;
}
if (!file_exists($path)) {//创建文件路径
mkdir($path, 0777);
}
$filename = $file["tmp_name"];
$image_size = getimagesize($filename);
$pinfo = pathinfo($file["name"]);
$ftype = $pinfo['extension']; //获取后缀
$destination = $path . time() . '_' . mt_rand(1000000, 9999999) . "." . $ftype;
if (file_exists($destination)) {
$msg_data['status'] = 0;
$msg_data['info'] = '已存在同名文件';
return $msg_data;
}
// die($filename);
if (!move_uploaded_file($filename, $destination)) {
$msg_data['status'] = 0;
$msg_data['info'] = '移动文件失败';
return $msg_data;
}
$pinfo = pathinfo($destination);
$fname = $pinfo['basename'];
$msg_data['status'] = 1;
$msg_data['path'] = str_replace($_SERVER['DOCUMENT_ROOT'], '', $destination);
$msg_data['size'] = $file['size'];
$msg_data['width'] = $image_size[0];
$msg_data['height'] = $image_size[1];
if ($upConfig['watermark'] == 1) {
$iinfo = getimagesize($destination, $iinfo);
$nimage = imagecreatetruecolor($image_size[0], $image_size[1]);
$white = imagecolorallocate($nimage, 255, 255, 255);
$black = imagecolorallocate($nimage, 0, 0, 0);
$red = imagecolorallocate($nimage, 255, 0, 0);
imagefill($nimage, 0, 0, $white);
switch ($iinfo[2]) {
case 1:
$simage = imagecreatefromgif($destination);
break;
case 2:
$simage = imagecreatefromjpeg($destination);
break;
case 3:
$simage = imagecreatefrompng($destination);
break;
case 6:
$simage = imagecreatefromwbmp($destination);
break;
default:
die("不支持的文件类型");
exit;
}
imagecopy($nimage, $simage, 0, 0, 0, 0, $image_size[0], $image_size[1]);
imagefilledrectangle($nimage, 1, $image_size[1] - 15, 80, $image_size[1], $white);
switch ($upConfig['watertype']) {
case 1: //加水印字符串
imagestring($nimage, 2, 3, $image_size[1] - 15, $upConfig['waterString'], $black);
break;
case 2: //加水印图片
$simage1 = imagecreatefrompng($upConfig['waterImage']);
imagecopy($nimage, $simage1, 0, 0, 0, 0, 85, 15);
imagedestroy($simage1);
break;
}
switch ($iinfo[2]) {
case 1:
//imagegif($nimage, $destination);
imagejpeg($nimage, $destination);
break;
case 2:
imagejpeg($nimage, $destination);
break;
case 3:
imagepng($nimage, $destination);
break;
case 6:
imagewbmp($nimage, $destination);
//imagejpeg($nimage, $destination);
break;
}
//覆盖原上传文件
imagedestroy($nimage);
imagedestroy($simage);
}
return $msg_data;
}
}
13、数据分页处理方法
public static function Page($total, $listData = 8) {
$totalRows = $total; //获取总数据条数
$listRows = 5;
$totalPage = ceil($totalRows / $listData); //获取总分页数
$totalColl = ceil($totalPage / $listRows); //获取分页栏总页数
$currentPage = !empty($_GET['start']) ? intval($_GET['start']) : 1; //获取当前页
$nowCoolPage = ceil($currentPage / $listRows); //获取当前分页栏数
$parameter = !empty($_GET) ? $_GET : array(); //获取参数
$parameter['start'] = '__PAGE__';
$url = $_SERVER['REDIRECT_URL'] . "?" . http_build_query($parameter); //获取当前url
//上下翻页字符串
$upRow = $currentPage - 1;
$downRow = $currentPage + 1;
//$pageShow = $totalRows."条记录/共".$totalPage."页 ";
if ($nowCoolPage == 1) {
$pageShow .= '';
} else {
$preRow = $currentPage - $listData;
$pageShow .= "首页";
/* $pageShow .= "上一列"; */
}
$pageShow .= $upRow > 0 ? "上一页" : "";
// 1 2 3 4 5
//add by baoxianjian 22:46 2015/4/2 分页点到5时,就从5到9
$i_start = 1;
$i_end = $listRows;
if (ceil(($currentPage + 1) / $listRows) > $nowCoolPage) {
$nowCoolPage++;
$i_start = 0;
$i_end = $listRows - 1;
}
for ($i = $i_start; $i <= $i_end; $i++) {
$page = ($nowCoolPage - 1) * $listRows + $i;
if ($currentPage != $page) {
if ($page <= $totalPage) {
$pageShow .= "" . $page . "";
} else {
// die($page);
break;
}
} else {
$pageShow .= "" . $page . "";
}
}
$pageShow .= $downRow <= $totalPage ? "下一页" : "";
if ($nowCoolPage < $totalColl && $nowCoolPage >= 1) {
/* $pageShow .= "下一列"; */
$pageShow .= "尾页";
}
return $pageShow;
}
14、错误转跳模板
public static function error($msg, $jumpUrl = '', $title = '错误提示', $wait = '', $TplUrl = '', $close = '') {
$jumpUrl !== '' && $config['jumpUrl'] = $jumpUrl;
$TplUrl !== '' && $config['TplUrl'] = $TplUrl;
$wait !== '' && $config['waitSecond'] = intval($wait);
$title !== '' && $config['title'] = $title;
$close !== '' && $config['closeWin'] = true;
$self = new self();
$self->dispatchJump($msg, 0, $config);
die;
}
15、成功转跳模板
public static function success($msg, $jumpUrl = '', $title = '成功提示', $wait = '', $TplUrl = '', $close = '') {
$TplUrl !== '' && $config['TplUrl'] = $TplUrl;
$jumpUrl !== '' && $config['jumpUrl'] = $jumpUrl;
$wait !== '' && $config['waitSecond'] = intval($wait);
$title !== '' && $config['title'] = $title;
$close !== '' && $config['closeWin'] = true;
$self = new self();
$self->dispatchJump($msg, 1, $config);
}
16、转跳提示模板
private function dispatchJump($msg, $status, $config) {
$sTpl = new STpl();
isset($config['title']) || $config['title'] = '提示信息';
isset($config['TplUrl']) || $config['TplUrl'] = "common/dispatchJump/dispatch_jump.html"; //检查模板是否存在
isset($config['closeWin']) && $config['jumpUrl'] = 'javascript:window.opener=null;window.close();'; //是否关闭窗口
$config['status'] = $status; //设置状态
if ($status) {//成功
$config['msg'] = $msg; //成功信息
isset($config['waitSecond']) || $config['waitSecond'] = '1'; //成功操作后默认停留1秒
// 默认操作成功自动返回操作前页面
isset($config['jumpUrl']) || $config['jumpUrl'] = $_SERVER["HTTP_REFERER"];
} else {//错误
$config['msg'] = $msg; //错误信息
isset($config['waitSecond']) || $config['waitSecond'] = '5'; //失败操作后默认停留5秒
// 默认操作成功自动返回操作前页面
isset($config['jumpUrl']) || $config['jumpUrl'] = "javascript:history.back(-1);";
}
echo $sTpl->render($config['TplUrl'], $config);
die;
}
17、判断异步请求处理方法
public static function isAjax() {
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
if ('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
return true;
}
//如果参数传递的参数中有ajax
if (!empty($_POST['ajax']) || !empty($_GET['ajax']))
return true;
return false;
}
18、判断post提交
public static function isPost() {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
return false;
}
return true;
}
19、判断get提交
public static function isGet() {
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
return false;
}
return true;
}
20、格式化打印数组处理方法
public static function P($arr) {
echo "";
print_r($arr);
}
21、读取配置数组文件处理方法
public static function C($name) {
require $_SERVER["DOCUMENT_ROOT"] . '/config_array.php';
return $config_array_php_file[$name];
}
22、过滤解释数组方法
public static function html_arr($arr) {
foreach ($arr as $k => $v) {
if (!is_array($v)) {
$arr[$k] = htmlspecialchars($v, ENT_QUOTES);
$arr[$k] = trim($arr[$k]);
} else {
$arr[$k] = self::html_arr($v);
}
}
return $arr;
}
23、 encode http请求过滤,防注入、XSS等安全处理 @param $string 可以为字符或者数组 @return $string 可以为字符或者数组
public static function httpFilter($string) {
$string = str_replace(array('sleep('), array('_sleep(_'), $string);
if (is_array($string)) {
foreach ($string as $key => $val) {
$string[$key] = self::httpFilter($val);
}
} else {
$string = trim($string);
$string = htmlspecialchars($string);
$string = self::straddslashes($string);
}
return $string;
}
private static function straddslashes($string) {
if (!get_magic_quotes_gpc()) {
return addslashes($string);
} else {
return $string;
}
}
24、decode http请求过滤,防注入、XSS等安全处理 返解码,最好不要使用 使用编辑器那么后面会自己写ubb规则来处理
public static function deHttpFilter($string) {
if (is_array($string)) {
foreach ($string as $key => $val) {
$string[$key] = self::deHttpFilter($val);
}
} else {
$string = htmlspecialchars_decode($string);
$string = stripslashes($string);
}
return $string;
}a
25、ubbl转html xheditor UBB使用 @param unknown_type $sUBB @return string|mixed
public static function ubb2html($sUBB) {
$sHtml = $sUBB;
global $emotPath, $cnum, $arrcode, $bUbb2htmlFunctionInit;
$cnum = 0;
$arrcode = array();
//表情目录 @todo 最后需要修改目录
$emotPath = IMAGE_URL . '/i/plugin/xheditor/xheditor_emot/'; //表情根路径
if (!$bUbb2htmlFunctionInit) {
function saveCodeArea($match) {
global $cnum, $arrcode;
$cnum++;
$arrcode[$cnum] = $match[0];
return "[\tubbcodeplace_" . $cnum . "\t]";
}
}
$sHtml = preg_replace_callback('/\[code\s*(?:=\s*((?:(?!")[\s\S])+?)(?:"[\s\S]*?)?)?\]([\s\S]*?)\[\/code\]/i', 'saveCodeArea', $sHtml);
$sHtml = preg_replace("/&/", '&', $sHtml);
$sHtml = preg_replace("/", '<', $sHtml);
$sHtml = preg_replace("/>/", '>', $sHtml);
$sHtml = preg_replace("/\r?\n/", '
', $sHtml);
$sHtml = preg_replace("/\[(\/?)(b|u|i|s|sup|sub)\]/i", '<$1$2>', $sHtml);
$sHtml = preg_replace('/\[color\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i', '', $sHtml);
if (!$bUbb2htmlFunctionInit) {
function getSizeName($match) {
$arrSize = array('10px', '13px', '16px', '18px', '24px', '32px', '48px');
if (preg_match("/^\d+$/", $match[1]))
$match[1] = $arrSize[$match[1] - 1];
return '';
}
}
$sHtml = preg_replace_callback('/\[size\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i', 'getSizeName', $sHtml);
$sHtml = preg_replace('/\[font\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i', '', $sHtml);
$sHtml = preg_replace('/\[back\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i', '', $sHtml);
$sHtml = preg_replace("/\[\/(color|size|font|back)\]/i", '', $sHtml);
for ($i = 0; $i < 3; $i++)
$sHtml = preg_replace('/\[align\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\](((?!\[align(?:\s+[^\]]+)?\])[\s\S])*?)\[\/align\]/', '$2
', $sHtml);
$sHtml = preg_replace('/\[img\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/img\]/i', '', $sHtml);
if (!$bUbb2htmlFunctionInit) {
function getImg($match) {
$alt = $match[1];
$p1 = $match[2];
$p2 = $match[3];
$p3 = $match[4];
$src = $match[5];
$a = $p3 ? $p3 : (!is_numeric($p1) ? $p1 : '');
return '';
}
}
$sHtml = preg_replace_callback('/\[img\s*=([^,\]]*)(?:\s*,\s*(\d*%?)\s*,\s*(\d*%?)\s*)?(?:,?\s*(\w+))?\s*\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*)?\s*\[\/img\]/i', 'getImg', $sHtml);
if (!$bUbb2htmlFunctionInit) {
function getEmot($match) {
global $emotPath;
$arr = explode(',', $match[1]);
if (!isset($arr[1])) {
$arr[1] = $arr[0];
$arr[0] = 'default';
}
$path = $emotPath . $arr[0] . '/' . $arr[1] . '.gif';
return '';
}
}
$sHtml = preg_replace_callback('/\[emot\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\/\]/i', 'getEmot', $sHtml);
$sHtml = preg_replace('/\[url\]\s*(((?!")[\s\S])*?)(?:"[\s\S]*?)?\s*\[\/url\]/i', '$1', $sHtml);
$sHtml = preg_replace('/\[url\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]*?)\s*\[\/url\]/i', '$2', $sHtml);
$sHtml = preg_replace('/\[email\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/email\]/i', '$1', $sHtml);
$sHtml = preg_replace('/\[email\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]+?)\s*\[\/email\]/i', '$2', $sHtml);
$sHtml = preg_replace("/\[quote\]/i", '', $sHtml);
$sHtml = preg_replace("/\[\/quote\]/i", '
', $sHtml);
if (!$bUbb2htmlFunctionInit) {
function getFlash($match) {
$w = $match[1];
$h = $match[2];
$url = $match[3];
if (!$w)
$w = 480;if (!$h)
$h = 400;
return '';
}
}
$sHtml = preg_replace_callback('/\[flash\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/flash\]/i', 'getFlash', $sHtml);
if (!$bUbb2htmlFunctionInit) {
function getMedia($match) {
$w = $match[1];
$h = $match[2];
$play = $match[3];
$url = $match[4];
if (!$w)
$w = 480;if (!$h)
$h = 400;
return '';
}
}
$sHtml = preg_replace_callback('/\[media\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+)\s*)?)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/media\]/i', 'getMedia', $sHtml);
if (!$bUbb2htmlFunctionInit) {
function getTable($match) {
return '';
}
}
$sHtml = preg_replace_callback('/\[table\s*(?:=(\d{1,4}%?)\s*(?:,\s*([^\]"]+)(?:"[^\]]*?)?)?)?\s*\]/i', 'getTable', $sHtml);
if (!$bUbb2htmlFunctionInit) {
function getTR($match) {
return '';
}
}
$sHtml = preg_replace_callback('/\[tr\s*(?:=(\s*[^\]"]+))?(?:"[^\]]*?)?\s*\]/i', 'getTR', $sHtml);
if (!$bUbb2htmlFunctionInit) {
function getTD($match) {
$col = isset($match[1]) ? $match[1] : 0;
$row = isset($match[2]) ? $match[2] : 0;
$w = isset($match[3]) ? $match[3] : null;
return ' 1 ? ' colspan="' . $col . '"' : '') . ($row > 1 ? ' rowspan="' . $row . '"' : '') . ($w ? ' width="' . $w . '"' : '') . '>';
}
}
$sHtml = preg_replace_callback("/\[td\s*(?:=\s*(\d{1,2})\s*,\s*(\d{1,2})\s*(?:,\s*(\d{1,4}%?))?)?\s*\]/i", 'getTD', $sHtml);
$sHtml = preg_replace("/\[\/(table|tr|td)\]/i", '$1>', $sHtml);
$sHtml = preg_replace("/\[\*\]((?:(?!\[\*\]|\[\/list\]|\[list\s*(?:=[^\]]+)?\])[\s\S])+)/i", '$1 ', $sHtml);
if (!$bUbb2htmlFunctionInit) {
function getUL($match) {
$str = '';
}
}
$sHtml = preg_replace_callback('/\[list\s*(?:=\s*([^\]"]+))?(?:"[^\]]*?)?\s*\]/i', 'getUL', $sHtml);
$sHtml = preg_replace("/\[\/list\]/i", '
', $sHtml);
$sHtml = preg_replace("/\[hr\/\]/i", '
', $sHtml);
for ($i = 1; $i <= $cnum; $i++)
$sHtml = str_replace("[\tubbcodeplace_" . $i . "\t]", $arrcode[$i], $sHtml);
if (!$bUbb2htmlFunctionInit) {
function fixText($match) {
$text = $match[2];
$text = preg_replace("/\t/", ' ', $text);
$text = preg_replace("/ /", ' ', $text);
return $match[1] . $text;
}
}
$sHtml = preg_replace_callback('/(^|<\/?\w+(?:\s+[^>]*?)?>)([^<$]+)/i', 'fixText', $sHtml);
$bUbb2htmlFunctionInit = true;
return $sHtml;
}
26、生成二维码
public static function getQrImg($chl, $widhtHeight = '120', $EC_level = 'L', $margin = '1') {
$chl = urlencode($chl);
$qr = 'http://chart.apis.google.com/chart?chs=' . $widhtHeight . 'x' . $widhtHeight . '&cht=qr&chld=' . $EC_level . '|' . $margin . '&chl=' . $chl;
return $qr;
}
a
27、全站统一 字符长度计算方法 中文占2个 英文数字占1个 数据库中char(10)的话是可以存的汉字与英文个数是一样的,都存10个,暂时网站暂使用这种方法测量字符串长度
public static function cp_strlen($str) {
return (strlen($str) + mb_strlen($str, 'UTF8')) / 2;
}
28、get substr support chinese 此函数是中文占用3个字符长度 return $str
public static function getSubStr($str, $start, $length, $postfix = '...', $encoding = 'UTF-8') {
$tlength = mb_strlen($str);
$str = mb_strcut($str, $start, $length, $encoding);
if ($tlength > $length) {
$str = $str . $postfix;
}
return $str;
}
29、get substr support chinese 此函数是中文占用2个字符长度 return $str
public static function getSubStr2($addr, $length, $suffix = '...') {
$len = strlen($addr);
if ($len > $length) {
for ($idx = 0; $idx < $length;) {
if (ord($addr[$idx]) > 0x7f) {
$length++;
$idx += 3;
} else {
$idx++;
}
}
return substr($addr, 0, $idx) . $suffix;
} else {
return $addr;
}
}
30、获取当前在线IP地址 @param $format @return $format = 0 返回IP地址:127.0.0.1 $format = 1 返回IP长整形:2130706433
public static function getIp($format = 0) {
global $_SGLOBAL;
if (empty($_SGLOBAL['onlineip'])) {
if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$onlineip = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$onlineip = getenv('REMOTE_ADDR');
} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$onlineip = $_SERVER['REMOTE_ADDR'];
}
preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
$_SGLOBAL['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
}
if (!$format) {
$ip = $_SGLOBAL['onlineip'];
} else {
$ip = sprintf('%u', ip2long($_SGLOBAL['onlineip']));
}
return $ip;
}
31、格式化大小函数 @param $size 为文件大小 @return 文件大小加单位
public static function formatsize($size) {
$prec = 3;
$size = round(abs($size));
$units = array(0 => " B ", 1 => " KB", 2 => " MB", 3 => " GB", 4 => " TB");
if ($size == 0)
return str_repeat(" ", $prec) . "0$units[0]";
$unit = min(4, floor(log($size) / log(2) / 10));
$size = $size * pow(2, -10 * $unit);
$digi = $prec - 1 - floor(log($size) / log(10));
$size = round($size * pow(10, $digi)) * pow(10, -$digi);
return $size . $units[$unit];
}
32、验证目录名是否有效 (只允许输入数字和字母) @param $dirname 目录名 @return true or false
public static function isdir($dirname) {
$patn = '/^[a-zA-Z]+[a-zA-Z0-9]+$/';
return preg_match($patn, $dirname);
}
33、创建目录 @param $path 目录路径 如:e:/work/yii/test @return true or false
public static function makePath($path) {
return is_dir($path) or ( self::makePath(dirname($path)) and mkdir($path, 0755));
}
34、 删除目录 @param $path 目录路径 如:e:/work/yii/test @return true or false
public static function rmDir($path) {
return @rmdir($path);
}
35、获取文件内容 @param $filename 目录路径 如:e:/work/yii/test.html @return 字符串->文件内容
public static function sreadfile($filename) {
$content = '';
if (function_exists('file_get_contents')) {
@$content = file_get_contents($filename);
} else {
if (@$fp = fopen($filename, 'r')) {
@$content = fread($fp, filesize($filename));
@fclose($fp);
}
}
return $content;
}
36、写入文件内容 @param $filename 目录路径 如:e:/work/yii/test.html @param $writetext 写入文件内容 @param $openmod 打开文件类型 默认为'w'表示写入 @return true or false
public static function swritefile($filename, $writetext, $openmod = 'w') {
if (@$fp = fopen($filename, $openmod)) {
flock($fp, 2);
fwrite($fp, $writetext);
fclose($fp);
return true;
} else {
//runlog('error', "File: $filename write error.");
return false;
}
}
37、 产生随机数 @param $length 产生随机数长度 @param $type 返回字符串类型 @param $hash 是否由前缀,默认为空. 如:$hash = 'zz-' 结果zz-823klis @return 随机字符串 $type = 0:数字+字母 $type = 1:数字 $type = 2:字符
public static function random($length, $type = 0, $hash = '') {
if ($type == 0) {
$chars = '23456789abcdefghijkmnpqrstuvwxyz';
} else if ($type == 1) {
$chars = '0123456789';
} else if ($type == 2) {
$chars = 'abcdefghijklmnopqrstuvwxyz';
}
//因为要用下标,32位肯定是0到31
$max = strlen($chars) - 1;
//microtime是返回当前时间截和微秒数,mt_srand是随机数
mt_srand((double) microtime() * 1000000);
//循环连接生成随机码
for ($i = 0; $i < $length; $i ++) {
$hash .= $chars [mt_rand(0, $max)];
}
return $hash;
}
38、取数组中的一列 返回 数组 或 逗号分隔的字符串
public static function getColumn($a = array(), $column = 'id', $isInt = 0, $retStr = true) {
$ret = array();
@list($column, $anc) = preg_split('/[\s\-]/', $column, 2, PREG_SPLIT_NO_EMPTY);
if ($a && is_array($a)) {
foreach ($a AS $one) {
if (@$one[$column])
$ret[] = ($isInt ? (int) @$one[$column] : @$one[$column]) . ($anc ? '-' . @$one[$anc] : '');
}
}
if ($retStr)
$ret = trim(@implode(',', $ret), ',');
return $ret;
}
/**
* object转为array
*/
public static function objToArray($stdclassobject) {
$_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;
if (empty($_array))
return array();
foreach ($_array as $key => $value) {
$value = (is_array($value) || is_object($value)) ? self::objToArray($value) : $value;
$array[$key] = $value;
}
return $array;
}
39、获取时间差 @param $begin_time 开始时间 @param $end_time 结束时间 @return 数组
public static function timediff($begin_time, $end_time) {
if ($begin_time > $end_time) {
return false; //time is wrong
} else {
$timediff = $end_time - $begin_time;
$days = intval($timediff / 86400);
$remain = $timediff % 86400;
$hours = intval($remain / 3600);
$remain = $remain % 3600;
$mins = intval($remain / 60);
$secs = $remain % 60;
$res = array("day" => $days, "hour" => $hours, "mins" => $mins, "sec" => $secs);
return $res;
}
}
40、格式化数字,以标准MONEY格式输出 @param $num 整型数字 @return 888,888,88
public static function formatnumber($num) {
return number_format($num, 2, ".", ",");
}
41、检测时间的正确性 @param $date 时间格式如:2010-04-05 @return true or false
public static function chkdate($date) {
if ((strpos($date, '-'))) {
$d = explode("-", $date);
if (checkdate($d[1], $d[2], $d[0])) {
return true;
} else {
return false;
}
} else {
return false;
}
}
42、cookie设置 @param $var 设置的cookie名 @param $value 设置的cookie值 @param $life 设置的过期时间:为整型,单位秒 如60表示60秒后过期 @param $path 设置的cookie作用路径 @param $domain 设置的cookie作用域名
public static function ssetcookie($array, $life = 0, $path = '/', $domain = COOKIE_DOMAIN) {
//global $_SERVER;
$_cookName_ary = array_keys($array);
for ($i = 0; $i < count($array); $i++) {
setcookie($_cookName_ary[$i], $array[$_cookName_ary[$i]], $life ? (time() + $life) : 0, $path, $domain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}
}
43、 密码是否够强 @param string $pass @return bool 是or否
public static function isStrongPass($pass) {
$RegExp = '/^[a-zA-z0-9\_\W]{6,16}$/'; //由大小写字母跟数字下划线组成并且长度在6-16字符直接
return preg_match($RegExp, $pass) ? true : false;
}
44、返回建议用户名 @param string username @return array 建议的用户名
public static function getRandomUsername($username, $count = 5) {
if (mb_strlen($username, 'utf-8') > 10) {
$username = self::utf8Substr($username, 0, rand(8, 10), '');
}
$wordsFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'filedata' . DIRECTORY_SEPARATOR . 'namedict.txt';
$contentArr = file($wordsFile);
//总行数
$totleLines = count($contentArr);
for ($i = 0; $i < $count; $i++) {
//随机行数
srand((double) microtime() * 1000000);
$current = mt_rand(0, $totleLines - 1);
$returnName[] = $username . '_' . str_replace("\r\n", '', $contentArr[$current]);
}
return $returnName;
}
45、过滤XSS攻击
static function reMoveXss($val) {
// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
// this prevents some character re-spacing such as
// note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
$val = preg_replace('/([\x00-\x08|\x0b-\x0c|\x0e-\x19])/', '', $val);
// straight replacements, the user should never need these since they're normal characters
// this prevents like
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
// ;? matches the ;, which is optional
// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
// @ @ search for the hex values
$val = preg_replace('/([xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
// @ @ 0{0,7} matches '0' zero to seven times
$val = preg_replace('/({0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
}
// now the only remaining whitespace attacks are \t, \n, and \r
$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', '
你可能感兴趣的:(【php常用方法】)