discuz开发者常用的php经典函数整理 [复制链接]
2871
0
- /**
- * 判断用户输入是否存在敏感词
- * 需要在ThinkPHP的ORG扩展文件夹中,添加敏感词类文件SensitiveFilter.php
- */
- function sensitive($content){
- //$arr=C('SENSITIVE');
- import("ORG.SensitiveFilter");
- $arr=SensitiveFilter::getWord();
- foreach ($arr as $v) {
- if (false !== strstr($content, $v)){
- $content=str_replace($v,'***',$content);//内容中存在敏感词库中的敏感词,则将敏感词用*替换
- }
- }
- return $content;
- }
复制代码
/**
*传递数据以易于阅读的样式格式化后输出
*/
- function p($data){
- // 定义样式
- $str='<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 13px;line-height: 1.42857;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
- // 如果是boolean或者null直接显示文字;否则print
- if (is_bool($data)) {
- $show_data=$data ? 'true' : 'false';
- }elseif (is_null($data)) {
- $show_data='null';
- }else{
- $show_data=print_r($data,true);
- }
- $str.=$show_data;
- $str.='</pre>';
- echo $str;
- }
复制代码
/**
* 判断用户输入是否存在敏感词
* 需要在ThinkPHP的ORG扩展文件夹中,添加敏感词类文件SensitiveFilter.php
*/
- function sensitive($content){
- //$arr=C('SENSITIVE');
- import("ORG.SensitiveFilter");
- $arr=SensitiveFilter::getWord();
- foreach ($arr as $v) {
- if (false !== strstr($content, $v)){
- $content=str_replace($v,'***',$content);//内容中存在敏感词库中的敏感词,则将敏感词用*替换
- }
- }
- return $content;
- }
复制代码
/**
*传递数据以易于阅读的样式格式化后输出
*/
- function p($data){
- // 定义样式
- $str='<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 13px;line-height: 1.42857;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
- // 如果是boolean或者null直接显示文字;否则print
- if (is_bool($data)) {
- $show_data=$data ? 'true' : 'false';
- }elseif (is_null($data)) {
- $show_data='null';
- }else{
- $show_data=print_r($data,true);
- }
- $str.=$show_data;
- $str.='</pre>';
- echo $str;
- }
复制代码
/**
* 删除指定的标签和内容
* @param array $tags 需要删除的标签数组
* @param string $str 数据源
* @param string $content 是否删除标签内的内容 0保留内容 1不保留内容
* @return string
*/
- function strip_html_tags($tags,$str,$content=0){
- if($content){
- $html=array();
- foreach ($tags as $tag) {
- $html[]='/([\s|\S]*?)/';
- }
- $data=preg_replace($html,'',$str);
- }else{
- $html=array();
- foreach ($tags as $tag) {
- $html[]="/(]*>)/i";
- }
- $data=preg_replace($html, '', $str);
- }
- return $data;
- }
复制代码
/**
* 传递ueditor生成的内容获取其中图片的路径
* @param string $str 含有图片链接的字符串
* @return array 匹配的图片数组
*/
- function get_ueditor_image_path($str){
- //$preg='/\/Upload\/zhuanti\/u(m)?editor\/\d*\/\d*\.[jpg|jpeg|png|bmp]*/i';
- $preg='';
- preg_match_all($preg, $str,$data);
- return current($data);
- }
复制代码
/**
* 字符串截取,支持中文和其他编码
* @param string $str 需要转换的字符串
* @param string $start 开始位置
* @param string $length 截取长度
* @param string $suffix 截断显示字符
* @param string $charset 编码格式
* @return string
*/
- function re_substr($str, $start=0, $length, $suffix=true, $charset="utf-8") {
- if(function_exists("mb_substr"))
- $slice = mb_substr($str, $start, $length, $charset);
- elseif(function_exists('iconv_substr')) {
- $slice = iconv_substr($str,$start,$length,$charset);
- }else{
- $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
- $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
- $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
- $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
- preg_match_all($re[$charset], $str, $match);
- $slice = join("",array_slice($match[0], $start, $length));
- }
- $omit=mb_strlen($str) >=$length ? '...' : '';
- return $suffix ? $slice.$omit : $slice;
- }
复制代码
/**
* 设置验证码,生成验证码字符串
* thinkphp自带验证码生成类
* @return 返回生成的验证码字符串
*/
- function show_verify($config=''){
- if($config==''){
- $config=array(
- 'codeSet'=>'1234567890',
- 'fontSize'=>30,
- 'useCurve'=>false,
- 'imageH'=>60,
- 'imageW'=>240,
- 'length'=>4,
- 'fontttf'=>'4.ttf',
- );
- }
- $verify=new \Think\Verify($config);
- return $verify->entry();
- }
复制代码
/**
* 取得根域名
* @param type $domain 域名
* @return string 返回根域名
*/
- function get_url_to_domain($domain) {
- $re_domain = '';
- $domain_postfix_cn_array = array("com", "net", "org", "gov", "edu", "com.cn", "cn");
- $array_domain = explode(".", $domain);
- $array_num = count($array_domain) - 1;
- if ($array_domain[$array_num] == 'cn') {
- if (in_array($array_domain[$array_num - 1], $domain_postfix_cn_array)) {
- $re_domain = $array_domain[$array_num - 2] . "." . $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
- } else {
- $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
- }
- } else {
- $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
- }
- return $re_domain;
- }
复制代码
/**
* 按符号截取字符串的指定部分
* @param string $str 需要截取的字符串
* @param string $sign 需要截取的符号
* @param int $number 如是正数以0为起点从左向右截 负数则从右向左截
* @return string 返回截取的内容
*/
/* 示例
$str='123/456/789';
cut_str($str,'/',0); 返回 123
cut_str($str,'/',-1); 返回 789
cut_str($str,'/',-2); 返回 456
具体参考 http://www.baijunyao.com/index.php/Home/Index/article/aid/18
*/
- function cut_str($str,$sign,$number){
- $array=explode($sign, $str);
- $length=count($array);
- if($number$length){
- return 'error';
- }else{
- return $new_array[$abs_number-1];
- }
- }else{
- if($number>=$length){
- return 'error';
- }else{
- return $array[$number];
- }
- }
- }
复制代码
/**
* 获取一定范围内的随机数字
* 跟rand()函数的区别是 位数不足补零 例如
* rand(1,9999)可能会得到 465
* rand_number(1,9999)可能会得到 0465 保证是4位的
* @param integer $min 最小值
* @param integer $max 最大值
* @return string
*/
- function rand_number ($min=1, $max=9999) {
- return sprintf("%0".strlen($max)."d", mt_rand($min,$max));
- }
复制代码
/**
* 生成一定数量的随机数,并且不重复
* @param integer $number 数量
* @param string $len 长度
* @param string $type 字串类型
* 0 字母 1 数字 其它 混合
* @return string
*/
- function build_count_rand ($number,$length=4,$mode=1) {
- if($mode==1 && $length<strlen($number) ) { ="" 不足以生成一定数量的不重复数字="" return false;="" }="" $rand =" array();" for($i="0; $i<$number; $i++) {" $rand[] =" rand_string($length,$mode);" $unqiue =" array_unique($rand);" if(count($unqiue)="=count($rand)) {" return $rand;="" $count =" count($rand)-count($unqiue);" $page="new_page($count,$limit);" ="" 获取分页数据="" $list="$model" -="">where($map)
- ->order($order)
- ->limit($page->firstRow.','.$page->listRows)
- ->select();
- $data=array(
- 'data'=>$list,
- 'page'=>$page->show()
- );
- return $data;
- }
- /**
- * 使用curl获取远程数据
- * @param string $url url连接
- * @return string 获取到的数据
- */
- [code]
- function curl_get_contents($url){
- $ch=curl_init();
- curl_setopt($ch, CURLOPT_URL, $url); //设置访问的url地址
- //curl_setopt($ch,CURLOPT_HEADER,1); //是否显示头部信息
- curl_setopt($ch, CURLOPT_TIMEOUT, 5); //设置超时
- curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_); //用户访问代理 User-Agent
- curl_setopt($ch, CURLOPT_REFERER,_REFERER_); //设置 referer
- curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); //跟踪301
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回结果
- $r=curl_exec($ch);
- curl_close($ch);
- return $r;
- }
- /*
- * 计算星座的函数 string get_zodiac_sign(string month, string day)
- * 输入:月份,日期
- * 输出:星座名称或者错误信息
- * 自学php博客www.zixuephp.cn整理
- */
- [code]
- function get_zodiac_sign($month, $day)
- {
- // 检查参数有效性
- if ($month 12 || $day 31)
- return (false);
- // 星座名称以及开始日期
- $signs = array(
- array( "20" => "水瓶座"),
- array( "19" => "双鱼座"),
- array( "21" => "白羊座"),
- array( "20" => "金牛座"),
- array( "21" => "双子座"),
- array( "22" => "巨蟹座"),
- array( "23" => "狮子座"),
- array( "23" => "处女座"),
- array( "23" => "天秤座"),
- array( "24" => "天蝎座"),
- array( "22" => "射手座"),
- array( "22" => "摩羯座")
- );
- list($sign_start, $sign_name) = each($signs[(int)$month-1]);
- if ($day < $sign_start)
- list($sign_start, $sign_name) = each($signs[($month -2 setAccount($accountSid,$accountToken);
- $rest->setAppId($appId);
- // 发送模板短信
- $result=$rest->sendTemplateSMS($phone,array($code,5),$templateId);
- if($result==NULL) {
- return false;
- }
- if($result->statusCode!=0) {
- return false;
- }else{
- return true;
- }
- }
复制代码
/**
* 将路径转换加密
* @param string $file_path 路径
* @return string 转换后的路径
*/
- function path_encode($file_path){
- return rawurlencode(base64_encode($file_path));
- }
复制代码
/**
* 将路径解密
* @param string $file_path 加密后的字符串
* @return string 解密后的路径
*/
- function path_decode($file_path){
- return base64_decode(rawurldecode($file_path));
- }
复制代码
/**
* 根据文件后缀的不同返回不同的结果
* @param string $str 需要判断的文件名或者文件的id
* @return integer 1:图片 2:视频 3:压缩文件 4:文档 5:其他
*/
- function file_category($str){
- // 取文件后缀名
- $str=strtolower(pathinfo($str, PATHINFO_EXTENSION));
- // 图片格式
- $images=array('webp','jpg','png','ico','bmp','gif','tif','pcx','tga','bmp','pxc','tiff','jpeg','exif','fpx','svg','psd','cdr','pcd','dxf','ufo','eps','ai','hdri');
- // 视频格式
- $video=array('mp4','avi','3gp','rmvb','gif','wmv','mkv','mpg','vob','mov','flv','swf','mp3','ape','wma','aac','mmf','amr','m4a','m4r','ogg','wav','wavpack');
- // 压缩格式
- $zip=array('rar','zip','tar','cab','uue','jar','iso','z','7-zip','ace','lzh','arj','gzip','bz2','tz');
- // 文档格式
- $document=array('exe','doc','ppt','xls','wps','txt','lrc','wfs','torrent','html','htm','java','js','css','less','php','pdf','pps','host','box','docx','word','perfect','dot','dsf','efe','ini','json','lnk','log','msi','ost','pcs','tmp','xlsb');
- // 匹配不同的结果
- switch ($str) {
- case in_array($str, $images):
- return 1;
- break;
- case in_array($str, $video):
- return 2;
- break;
- case in_array($str, $zip):
- return 3;
- break;
- case in_array($str, $document):
- return 4;
- break;
- default:
- return 5;
- break;
- }
- }
复制代码
/**
* 组合缩略图
* @param string $file_path 原图path
* @param integer $size 比例
* @return string 缩略图
*/
- function get_min_image_path($file_path,$width=170,$height=170){
- $min_path=str_replace('.', '_'.$width.'_'.$height.'.', trim($file_path,'.'));
- $min_path='http://xueba17.oss-cn-beijing.aliyuncs.com'.$min_path;
- return $min_path;
- }
复制代码
/**
* 不区分大小写的in_array()
* @param string $str 检测的字符
* @param array $array 数组
* @return boolear 是否in_array
*/
- function in_iarray($str,$array){
- $str=strtolower($str);
- $array=array_map('strtolower', $array);
- if (in_array($str, $array)) {
- return true;
- }
- return false;
- }
复制代码
/**
* 传入时间戳,计算距离现在的时间
* @param number $time 时间戳
* @return string 返回多少以前
*/
- function word_time($time) {
- $time = (int) substr($time, 0, 10);
- $int = time() - $time;
- $str = '';
- if ($int <= 2){
- $str = sprintf('刚刚', $int);
- }elseif ($int < 60){
- $str = sprintf('%d秒前', $int);
- }elseif ($int < 3600){
- $str = sprintf('%d分钟前', floor($int / 60));
- }elseif ($int open($image_path);
- // 生成一个居中裁剪为$width*$height的缩略图并保存
- $image->thumb($width, $height,\Think\Image::IMAGE_THUMB_CENTER)->save($min_path);
- oss_upload($min_path);
- return $min_path;
- }
复制代码
/**
* 把用户输入的文本转义(主要针对特殊符号和emoji表情)
*/
- function emoji_encode($str){
- if(!is_string($str))return $str;
- if(!$str || $str=='undefined')return '';
- $text = json_encode($str); //暴露出unicode
- $text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
- return addslashes($str[0]);
- },$text); //将emoji的unicode留下,其他不动,这里的正则比原答案增加了d,因为我发现我很多emoji实际上是\ud开头的,反而暂时没发现有\ue开头。
- return json_decode($text);
- }
复制代码
/**
* 检测是否是手机访问
*/
- function is_mobile(){
- $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
- $useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';
- [code]
- function _is_mobile($substrs,$text){
- foreach($substrs as $substr)
- if(false!==strpos($text,$substr)){
- return true;
- }
- return false;
- }
- $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
- $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');
- $found_mobile=_is_mobile($mobile_os_list,$useragent_commentsblock) ||
- _is_mobile($mobile_token_list,$useragent);
- if ($found_mobile){
- return true;
- }else{
- return false;
- }
- }
复制代码
/**
* 将utf-16的emoji表情转为utf8文字形
* @param string $str 需要转的字符串
* @return string 转完成后的字符串
*/
- function escape_sequence_decode($str) {
- $regex = '/\\\u([dD][89abAB][\da-fA-F]{2})\\\u([dD][c-fC-F][\da-fA-F]{2})|\\\u([\da-fA-F]{4})/sx';
- return preg_replace_callback($regex, function($matches) {
- if (isset($matches[3])) {
- $cp = hexdec($matches[3]);
- } else {
- $lead = hexdec($matches[1]);
- $trail = hexdec($matches[2]);
- $cp = ($lead << 10) + $trail + 0x10000 - (0xD800 < 0xD7FF && 0xE000 > $cp) {
- $cp = 0xFFFD;
- }
- if ($cp < 0x80) {
- return chr($cp);
- } else if ($cp > 6).chr(0x80 | $cp & 0x3F);
- }
- $result = html_entity_decode('&#'.$cp.';');
- return $result;
- }, $str);
- }
复制代码
/**
* 获取当前访问的设备类型
* @return integer 1:其他 2:iOS 3:Android
*/
- function get_device_type(){
- //全部变成小写字母
- $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
- $type = 1;
- //分别进行判断
- if(strpos($agent, 'iphone')!==false || strpos($agent, 'ipad')!==false){
- $type = 2;
- }
- if(strpos($agent, 'android')!==false){
- $type = 3;
- }
- return $type;
- }
复制代码
/**
* 生成pdf
* @param string $html 需要生成的内容
*/
- function pdf($html='hello word'){
- vendor('Tcpdf.tcpdf');
- $pdf = new \Tcpdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
- // 设置打印模式
- $pdf->SetCreator(PDF_CREATOR);
- $pdf->SetAuthor('Nicola Asuni');
- $pdf->SetTitle('TCPDF Example 001');
- $pdf->SetSubject('TCPDF Tutorial');
- $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
- // 是否显示页眉
- $pdf->setPrintHeader(false);
- // 设置页眉显示的内容
- $pdf->SetHeaderData('logo.png', 60, 'baijunyao.com', '白俊遥博客', array(0,64,255), array(0,64,128));
- // 设置页眉字体
- $pdf->setHeaderFont(Array('dejavusans', '', '12'));
- // 页眉距离顶部的距离
- $pdf->SetHeaderMargin('5');
- // 是否显示页脚
- $pdf->setPrintFooter(true);
- // 设置页脚显示的内容
- $pdf->setFooterData(array(0,64,0), array(0,64,128));
- // 设置页脚的字体
- $pdf->setFooterFont(Array('dejavusans', '', '10'));
- // 设置页脚距离底部的距离
- $pdf->SetFooterMargin('10');
- // 设置默认等宽字体
- $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
- // 设置行高
- $pdf->setCellHeightRatio(1);
- // 设置左、上、右的间距
- $pdf->SetMargins('10', '10', '10');
- // 设置是否自动分页 距离底部多少距离时分页
- $pdf->SetAutoPageBreak(TRUE, '15');
- // 设置图像比例因子
- $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
- if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
- require_once(dirname(__FILE__).'/lang/eng.php');
- $pdf->setLanguageArray($l);
- }
- $pdf->setFontSubsetting(true);
- $pdf->AddPage();
- // 设置字体
- $pdf->SetFont('stsongstdlight', '', 14, '', true);
- $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
- $pdf->Output('example_001.pdf', 'I');
- }
复制代码
/**
* 生成二维码
* @param string $url url连接
* @param integer $size 尺寸 纯数字
*/
- function qrcode($url,$size=4){
- Vendor('Phpqrcode.phpqrcode');
- QRcode::png($url,false,QR_ECLEVEL_L,$size,2,false,0xFFFFFF,0x000000);
- }
复制代码
/**
* 数组转xls格式的excel文件
* @param array $data 需要生成excel文件的数组
* @param string $filename 生成的excel文件名
* 示例数据:
$data = array(
array(NULL, 2010, 2011, 2012),
array('Q1', 12, 15, 21),
array('Q2', 56, 73, 86),
array('Q3', 52, 61, 69),
array('Q4', 30, 32, 0),
);
*/
- function create_xls($data,$filename='simple.xls'){
- ini_set('max_execution_time', '0');
- Vendor('PHPExcel.PHPExcel');
- $filename=str_replace('.xls', '', $filename).'.xls';
- $phpexcel = new PHPExcel();
- $phpexcel->getProperties()
- ->setCreator("Maarten Balliauw")
- ->setLastModifiedBy("Maarten Balliauw")
- ->setTitle("Office 2007 XLSX Test Document")
- ->setSubject("Office 2007 XLSX Test Document")
- ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
- ->setKeywords("office 2007 openxml php")
- ->setCategory("Test result file");
- $phpexcel->getActiveSheet()->fromArray($data);
- $phpexcel->getActiveSheet()->setTitle('Sheet1');
- $phpexcel->setActiveSheetIndex(0);
- header('Content-Type: application/vnd.ms-excel');
- header("Content-Disposition: attachment;filename=$filename");
- header('Cache-Control: max-age=0');
- header('Cache-Control: max-age=1');
- header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
- header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
- header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
- header ('Pragma: public'); // HTTP/1.0
- $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
- $objwriter->save('php://output');
- exit;
- }
复制代码
/**
* 数据转csv格式的excel
* @param array $data 需要转的数组
* @param string $filename 生成的excel文件名
* 示例数组:
$a = array(
'1,2,3,4,5',
'6,7,8,9,0',
'1,3,5,6,7'
);
*/
- function create_csv($data,$filename='simple.csv'){
- // 防止没有添加文件后缀
- $filename=str_replace('.csv', '', $filename).'.csv';
- Header( "Content-type: application/octet-stream ");
- Header( "Accept-Ranges: bytes ");
- Header( "Content-Disposition: attachment; filename=".$filename);
- foreach( $data as $k => $v){
- // 替换掉换行
- $v=preg_replace('/\s*/', '', $v);
- // 转成gbk以兼容office乱码的问题
- echo iconv('UTF-8','GBK',$v)."\r\n";
- }
- }
复制代码
/**
* 判断当前服务器系统
* @return string
*/
- function getOS(){
- if(PATH_SEPARATOR == ':'){
- return 'Linux';
- }else{
- return 'Windows';
- }
- }
复制代码
/**
* 当前微妙数
* @return number
*/
- function microtime_float() {
- list ( $usec, $sec ) = explode ( " ", microtime () );
- return (( float ) $usec + ( float ) $sec);
- }
复制代码
/**
* 遍历文件夹
* @param string $dir
* @param boolean $all true表示递归遍历
* @return array
*/
- function scanfDir($dir='', $all = false, &$ret = array()){
- if ( false !== ($handle = opendir ( $dir ))) {
- while ( false !== ($file = readdir ( $handle )) ) {
- if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) {
- $cur_path = $dir . '/' . $file;
- if (is_dir ( $cur_path )) {
- $ret['dirs'][] =$cur_path;
- $all && self::scanfDir( $cur_path, $all, $ret);
- } else {
- $ret ['files'] [] = $cur_path;
- }
- }
- }
- closedir ( $handle );
- }
- return $ret;
- }
复制代码
/**
* 判断字符串是utf-8 还是gb2312
* @param unknown $str
* @param string $default
* @return string
*/
- function utf8_gb2312($str, $default = 'gb2312')
- {
- $str = preg_replace("/[\x01-\x7F]+/", "", $str);
- if (empty($str)) return $default;
- $preg = array(
- "gb2312" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正则判断是否是gb2312
- "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u", //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了
- );
- if ($default == 'gb2312') {
- $option = 'utf-8';
- } else {
- $option = 'gb2312';
- }
- if (!preg_match($preg[$default], $str)) {
- return $option;
- }
- $str = @iconv($default, $option, $str);
- //不能转成 $option, 说明原来的不是 $default
- if (empty($str)) {
- return $option;
- }
- return $default;
- }
复制代码
/**
* utf-8和gb2312自动转化
* @param unknown $string
* @param string $outEncoding
* @return unknown|string
*/
- function safeEncoding($string,$outEncoding = 'UTF-8')
- {
- $encoding = "UTF-8";
- for($i = 0; $i < strlen ( $string ); $i ++) {
- if (ord ( $string {$i} ) $v){
- $ret[$k] = $v[$key];
- }
- return $ret;
- }
复制代码
/**
* 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数)
* @param string $file 文件/目录
* @return boolean
*/
- function is_writeable($file) {
- if (is_dir($file)){
- $dir = $file;
- if ($fp = @fopen("$dir/test.txt", 'w')) {
- @fclose($fp);
- @unlink("$dir/test.txt");
- $writeable = 1;
- } else {
- $writeable = 0;
- }
- } else {
- if ($fp = @fopen($file, 'a+')) {
- @fclose($fp);
- $writeable = 1;
- } else {
- $writeable = 0;
- }
- }
- return $writeable;
- }
复制代码
/**
* 格式化单位
*/
- function byteFormat( $size, $dec = 2 ) {
- $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );
- $pos = 0;
- while ( $size >= 1024 ) {
- $size /= 1024;
- $pos ++;
- }
- return round( $size, $dec ) . " " . $a[$pos];
- }
复制代码
/**
* 下拉框,单选按钮 自动选择
* @param $string 输入字符
* @param $param 条件
* @param $type 类型
* selected checked
* @return string
*/
- function selected( $string, $param = 1, $type = 'select' ) {
- $true = false;
- if ( is_array( $param ) ) {
- $true = in_array( $string, $param );
- }elseif ( $string == $param ) {
- $true = true;
- }
- $return='';
- if ( $true )
- $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';
- echo $return;
- }
复制代码
/**
* 下载远程图片
* @param string $url 图片的绝对url
* @param string $filepath 文件的完整路径(例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名
* @param string $filename 要保存的文件名(不含扩展名)
* @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false
*/
- function downloadImage($url, $filepath, $filename) {
- //服务器返回的头信息
- $responseHeaders = array();
- //原始图片名
- $originalfilename = '';
- //图片的后缀名
- $ext = '';
- $ch = curl_init($url);
- //设置curl_exec返回的值包含Http头
- curl_setopt($ch, CURLOPT_HEADER, 1);
- //设置curl_exec返回的值包含Http内容
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- //设置抓取跳转(http 301,302)后的页面
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
- //设置最多的HTTP重定向的数量
- curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
- //服务器返回的数据(包括http头信息和内容)
- $html = curl_exec($ch);
- //获取此次抓取的相关信息
- $httpinfo = curl_getinfo($ch);
- curl_close($ch);
- if ($html !== false) {
- //分离response的header和body,由于服务器可能使用了302跳转,所以此处需要将字符串分离为 2+跳转次数 个子串
- $httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);
- //倒数第二段是服务器最后一次response的http头
- $header = $httpArr[count($httpArr) - 2];
- //倒数第一段是服务器最后一次response的内容
- $body = $httpArr[count($httpArr) - 1];
- $header.="\r\n";
- //获取最后一次response的header信息
- preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);
- if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) {
- for ($i = 0; $i < count($matches[1]); $i++) {
- if (array_key_exists($i, $matches[2])) {
- $responseHeaders[$matches[1][$i]] = $matches[2][$i];
- }
- }
- }
- //获取图片后缀名
- if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {
- $originalfilename = $matches[0];
- $ext = $matches[1];
- } else {
- if (array_key_exists('Content-Type', $responseHeaders)) {
- if (0 realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));
- }
- }
- }
- }
- return false;
- }
复制代码
/**
* 查找ip是否在某个段位里面
* @param string $ip 要查询的ip
* @param $arrIP 禁止的ip
* @return boolean
*/
- function ipAccess($ip='0.0.0.0', $arrIP = array()){
- $access = true;
- $ip && $arr_cur_ip = explode('.', $ip);
- foreach((array)$arrIP as $key=> $value){
- if($value == '*.*.*.*'){
- $access = false; //禁止所有
- break;
- }
- $tmp_arr = explode('.', $value);
- if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) {
- //前两段相同
- if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){
- //第三段为* 或者相同
- if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){
- //第四段为* 或者相同
- $access = false; //在禁止ip列,则禁止访问
- break;
- }
- }
- }
- }
- return $access;
- }
复制代码
/**
* @param string $string 原文或者密文
* @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
* @param string $key 密钥
* @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效
* @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
* @example
* $a = authcode('abc', 'ENCODE', 'key');
* $b = authcode($a, 'DECODE', 'key'); // $b(abc)
* $a = authcode('abc', 'ENCODE', 'key', 3600);
* $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空
*/
- function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {
- $ckey_length = 4;
- // 随机密钥长度 取值 0-32;
- // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。
- // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方
- // 当此值为 0 时,则不产生随机密钥
- $key = md5 ( $key ? $key : 'key' ); //这里可以填写默认key值
- $keya = md5 ( substr ( $key, 0, 16 ) );
- $keyb = md5 ( substr ( $key, 16, 16 ) );
- $keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';
- $cryptkey = $keya . md5 ( $keya . $keyc );
- $key_length = strlen ( $cryptkey );
- $string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
- $string_length = strlen ( $string );
- $result = '';
- $box = range ( 0, 255 );
- $rndkey = array ();
- for($i = 0; $i <= 255; $i ++) {
- $rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
- }
- for($j = $i = 0; $i < 256; $i ++) {
- $j = ($j + $box [$i] + $rndkey [$i]) % 256;
- $tmp = $box [$i];
- $box [$i] = $box [$j];
- $box [$j] = $tmp;
- }
- for($a = $j = $i = 0; $i 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
- return substr ( $result, 26 );
- } else {
- return '';
- }
- } else {
- return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
- }
- }
复制代码
/**
* gbk转utf-8格式方法
*/
- function gbkToUtf8($str){
- return iconv("GBK", "UTF-8", $str);
- }
复制代码
/**
* 取得输入目录所包含的所有目录和文件
* 以关联数组形式返回
* author: flynetcn
*/
- function deepScanDir($dir)
- {
- $fileArr = array();
- $dirArr = array();
- $dir = rtrim($dir, '//');
- if(is_dir($dir)){
- $dirHandle = opendir($dir);
- while(false !== ($fileName = readdir($dirHandle))){
- $subFile = $dir . DIRECTORY_SEPARATOR . $fileName;
- if(is_file($subFile)){
- $fileArr[] = $subFile;
- } elseif (is_dir($subFile) && str_replace('.', '', $fileName)!=''){
- $dirArr[] = $subFile;
- $arr = self::deepScanDir($subFile);
- $dirArr = array_merge($dirArr, $arr['dir']);
- $fileArr = array_merge($fileArr, $arr['file']);
- }
- }
- closedir($dirHandle);
- }
- return array('dir'=>$dirArr, 'file'=>$fileArr);
- }
复制代码
/**
* 取得输入目录所包含的所有文件
* 以数组形式返回
* author: flynetcn
*/
- function get_dir_files($dir)
- {
- if (is_file($dir)) {
- return array($dir);
- }
- $files = array();
- if (is_dir($dir) && ($dir_p = opendir($dir))) {
- $ds = DIRECTORY_SEPARATOR;
- while (($filename = readdir($dir_p)) !== false) {
- if ($filename=='.' || $filename=='..') { continue; }
- $filetype = filetype($dir.$ds.$filename);
- if ($filetype == 'dir') {
- $files = array_merge($files, self::get_dir_files($dir.$ds.$filename));
- } elseif ($filetype == 'file') {
- $files[] = $dir.$ds.$filename;
- }
- }
- closedir($dir_p);
- }
- return $files;
- }
复制代码
/**
* 删除文件夹及其文件夹下所有文件
*/
- function deldir($dir) {
- //先删除目录下的文件:
- $dh=opendir($dir);
- while ($file=readdir($dh)) {
- if($file!="." && $file!="..") {
- $fullpath=$dir."/".$file;
- if(!is_dir($fullpath)) {
- unlink($fullpath);
- } else {
- self::deldir($fullpath);
- }
- }
- }
- closedir($dh);
- //删除当前文件夹:
- if(rmdir($dir)) {
- return true;
- } else {
- return false;
- }
- }
复制代码
/**
* js 弹窗返回
* @param string $_info
* @return js
*/
- function alertBack($_info) {
- echo "";
- exit();
- }
复制代码
/**
* html过滤
* @param array|object $_date
* @return string
*/
- function htmlString($_date) {
- if (is_array($_date)) {
- foreach ($_date as $_key=>$_value) {
- $_string[$_key] = self::htmlString($_value); //递归
- }
- } elseif (is_object($_date)) {
- foreach ($_date as $_key=>$_value) {
- $_string->$_key = self::htmlString($_value); //递归
- }
- } else {
- $_string = htmlspecialchars($_date);
- }
- return $_string;
- }
复制代码
/**
* 数据库输入过滤
* @param string $_data
* @return string
*/
- function mysqlString($_data) {
- $_data = trim($_data);
- return !GPC ? addcslashes($_data) : $_data;
- }
复制代码
/**
* 清理session
*/
- function unSession() {
- if (session_start()) {
- session_destroy();
- }
- }
复制代码
/**
* 格式化字符串
* @param string $str
* @return string
*/
- function formatStr($str) {
- $arr = array(' ', ' ', '&', '@', '#', '%', '\'', '"', '\\', '/', '.', ',', '
- /**
- * 格式化时间
- * @param int $time 时间戳
- * @return string
- */
- [code]
- function formatDate($time='default') {
- $date = $time == 'default' ? date('Y-m-d H:i:s', time()) : date('Y-m-d H:i:s', $time);
- return $date;
- }
复制代码
/**
* 获得真实IP地址
* @return string
*/
- function realIp() {
- static $realip = NULL;
- if ($realip !== NULL) return $realip;
- if (isset($_SERVER)) {
- if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
- $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
- foreach ($arr AS $ip) {
- $ip = trim($ip);
- if ($ip != 'unknown') {
- $realip = $ip;
- break;
- }
- }
- } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
- $realip = $_SERVER['HTTP_CLIENT_IP'];
- } else {
- if (isset($_SERVER['REMOTE_ADDR'])) {
- $realip = $_SERVER['REMOTE_ADDR'];
- } else {
- $realip = '0.0.0.0';
- }
- }
- } else {
- if (getenv('HTTP_X_FORWARDED_FOR')) {
- $realip = getenv('HTTP_X_FORWARDED_FOR');
- } elseif (getenv('HTTP_CLIENT_IP')) {
- $realip = getenv('HTTP_CLIENT_IP');
- } else {
- $realip = getenv('REMOTE_ADDR');
- }
- }
- preg_match('/[\d\.]{7,15}/', $realip, $onlineip);
- $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
- return $realip;
- }
复制代码
/**
* 创建目录
* @param string $dir
*/
- function createDir($dir) {
- if (!is_dir($dir)) {
- mkdir($dir, 0777);
- }
- }
复制代码
/**
* 创建文件(默认为空)
* @param unknown_type $filename
*/
- function createFile($filename) {
- if (!is_file($filename)) touch($filename);
- }
复制代码
/**
* 正确获取变量
* @param string $param
* @param string $type
* @return string
*/
- function getData($param, $type='post') {
- $type = strtolower($type);
- if ($type=='post') {
- return self::mysqlString(trim($_POST[$param]));
- } elseif ($type=='get') {
- return self::mysqlString(trim($_GET[$param]));
- }
- }
复制代码
/**
* 删除文件
* @param string $filename
*/
- function delFile($filename) {
- if (file_exists($filename)) unlink($filename);
- }
复制代码
/**
* 删除目录
* @param string $path
*/
- function delDir($path) {
- if (is_dir($path)) rmdir($path);
- }
复制代码
/**
* 删除目录及全部子文件
* @param string $dir
* @return bool
*/
- function delDirOfAll($dir) {
- //先删除目录下的文件:
- if (is_dir($dir)) {
- $dh=opendir($dir);
- while (!!$file=readdir($dh)) {
- if($file!="." && $file!="..") {
- $fullpath=$dir."/".$file;
- if(!is_dir($fullpath)) {
- unlink($fullpath);
- } else {
- self::delDirOfAll($fullpath);
- }
- }
- }
- closedir($dh);
- //删除当前文件夹:
- if(rmdir($dir)) {
- return true;
- } else {
- return false;
- }
- }
- }
复制代码
/**
* 给已经存在的图片添加水印
* @param string $file_path
* @return bool
*/
- function addMark($file_path) {
- if (file_exists($file_path) && file_exists(MARK)) {
- //求出上传图片的名称后缀
- $ext_name = strtolower(substr($file_path, strrpos($file_path, '.'), strlen($file_path)));
- //$new_name='jzy_' . time() . rand(1000,9999) . $ext_name ;
- $store_path = ROOT_PATH . UPDIR;
- //求上传图片高宽
- $imginfo = getimagesize($file_path);
- $width = $imginfo[0];
- $height = $imginfo[1];
- //添加图片水印
- switch($ext_name) {
- case '.gif':
- $dst_im = imagecreatefromgif($file_path);
- break;
- case '.jpg':
- $dst_im = imagecreatefromjpeg($file_path);
- break;
- case '.png':
- $dst_im = imagecreatefrompng($file_path);
- break;
- }
- $src_im = imagecreatefrompng(MARK);
- //求水印图片高宽
- $src_imginfo = getimagesize(MARK);
- $src_width = $src_imginfo[0];
- $src_height = $src_imginfo[1];
- //求出水印图片的实际生成位置
- $src_x = $width - $src_width - 10;
- $src_y = $height - $src_height - 10;
- //新建一个真彩色图像
- $nimage = imagecreatetruecolor($width, $height);
- //拷贝上传图片到真彩图像
- imagecopy($nimage, $dst_im, 0, 0, 0, 0, $width, $height);
- //按坐标位置拷贝水印图片到真彩图像上
- imagecopy($nimage, $src_im, $src_x, $src_y, 0, 0, $src_width, $src_height);
- //分情况输出生成后的水印图片
- switch($ext_name) {
- case '.gif':
- imagegif($nimage, $file_path);
- break;
- case '.jpg':
- imagejpeg($nimage, $file_path);
- break;
- case '.png':
- imagepng($nimage, $file_path);
- break;
- }
- //释放资源
- imagedestroy($dst_im);
- imagedestroy($src_im);
- unset($imginfo);
- unset($src_imginfo);
- //移动生成后的图片
- @move_uploaded_file($file_path, ROOT_PATH.UPDIR . $file_path);
- }
- }
复制代码
/**
* 中文截取2,单字节截取模式
* @access public
* @param string $str 需要截取的字符串
* @param int $slen 截取的长度
* @param int $startdd 开始标记处
* @return string
*/
- function cn_substr($str, $slen, $startdd=0){
- $cfg_soft_lang = PAGECHARSET;
- if($cfg_soft_lang=='utf-8') {
- return self::cn_substr_utf8($str, $slen, $startdd);
- }
- $restr = '';
- $c = '';
- $str_len = strlen($str);
- if($str_len < $startdd+1) {
- return '';
- }
- if($str_len 0x80) {
- if($str_len>$i+1) {
- $c = $str[$i].$str[$i+1];
- }
- $i++;
- } else {
- $c = $str[$i];
- }
- if($i >= $enddd) {
- if(strlen($restr)+strlen($c)>$slen) {
- break;
- } else {
- $restr .= $c;
- break;
- }
- }
- }
- return $restr;
- }
复制代码
/**
* utf-8中文截取,单字节截取模式
* @access public
* @param string $str 需要截取的字符串
* @param int $slen 截取的长度
* @param int $startdd 开始标记处
* @return string
*/
- function cn_substr_utf8($str, $length, $start=0) {
- if(strlen($str) < $start+1) {
- return '';
- }
- preg_match_all("/./su", $str, $ar);
- $str = '';
- $tstr = '';
- //为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取
- for($i=0; isset($ar[0][$i]); $i++) {
- if(strlen($tstr) < $start) {
- $tstr .= $ar[0][$i];
- } else {
- if(strlen($str) getOne($db_name, "i.id={$image_id}", "i.path as p, i.big_img as b, i.small_img as s");
- foreach ($data as $v) {
- @self::delFile(ROOT_PATH . $v['p']);
- @self::delFile(ROOT_PATH . $v['b']);
- @self::delFile(ROOT_PATH . $v['s']);
- }
- $m->del(PREFIX . 'images', "id={$image_id}");
- unset($m);
- }
复制代码
/**
* 图片等比例缩放
* @param resource $im 新建图片资源(imagecreatefromjpeg/imagecreatefrompng/imagecreatefromgif)
* @param int $maxwidth 生成图像宽
* @param int $maxheight 生成图像高
* @param string $name 生成图像名称
* @param string $filetype文件类型(.jpg/.gif/.png)
*/
- function resizeImage($im, $maxwidth, $maxheight, $name, $filetype) {
- $pic_width = imagesx($im);
- $pic_height = imagesy($im);
- if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
- if($maxwidth && $pic_width>$maxwidth) {
- $widthratio = $maxwidth/$pic_width;
- $resizewidth_tag = true;
- }
- if($maxheight && $pic_height>$maxheight) {
- $heightratio = $maxheight/$pic_height;
- $resizeheight_tag = true;
- }
- if($resizewidth_tag && $resizeheight_tag) {
- if($widthratio0)) {
- $file_data = fread($fp, $buffer);
- $file_count += $buffer;
- echo $file_data;
- }
- fclose($fp); //关闭文件
- }
复制代码
历史资源提醒--必看
该页面资源/教程来自原魔趣吧历史资源转移,因发布历史久远,部分资源/教程可能已失效或无法在最新版程序中安装使用!DZ资源建议在Discuz3.4及以下版本使用,PHP版本建议5.6。资源仅提供做代码研究学习使用!
因改版,部分贴内链接将无法正常跳转,如链接失效或未正常跳转,请利用站内搜索功能搜索资源名称获取对应资源!
最新回复 (0)