discuz开发者常用的php经典函数整理 [复制链接]

moqu8 2018-1-15

2871 0

  1. /**
  2. * 判断用户输入是否存在敏感词
  3. * 需要在ThinkPHP的ORG扩展文件夹中,添加敏感词类文件SensitiveFilter.php
  4. */
  5. function sensitive($content){
  6. //$arr=C('SENSITIVE');
  7. import("ORG.SensitiveFilter");
  8. $arr=SensitiveFilter::getWord();
  9. foreach ($arr as $v) {
  10. if (false !== strstr($content, $v)){
  11. $content=str_replace($v,'***',$content);//内容中存在敏感词库中的敏感词,则将敏感词用*替换
  12. }
  13. }
  14. return $content;
  15. }

复制代码


/**
*传递数据以易于阅读的样式格式化后输出
*/

  1. function p($data){
  2. // 定义样式
  3. $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;">';
  4. // 如果是boolean或者null直接显示文字;否则print
  5. if (is_bool($data)) {
  6. $show_data=$data ? 'true' : 'false';
  7. }elseif (is_null($data)) {
  8. $show_data='null';
  9. }else{
  10. $show_data=print_r($data,true);
  11. }
  12. $str.=$show_data;
  13. $str.='</pre>';
  14. echo $str;
  15. }

复制代码



/**
* 判断用户输入是否存在敏感词
* 需要在ThinkPHP的ORG扩展文件夹中,添加敏感词类文件SensitiveFilter.php
*/

  1. function sensitive($content){
  2. //$arr=C('SENSITIVE');
  3. import("ORG.SensitiveFilter");
  4. $arr=SensitiveFilter::getWord();
  5. foreach ($arr as $v) {
  6. if (false !== strstr($content, $v)){
  7. $content=str_replace($v,'***',$content);//内容中存在敏感词库中的敏感词,则将敏感词用*替换
  8. }
  9. }
  10. return $content;
  11. }

复制代码



/**
*传递数据以易于阅读的样式格式化后输出
*/

  1. function p($data){
  2. // 定义样式
  3. $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;">';
  4. // 如果是boolean或者null直接显示文字;否则print
  5. if (is_bool($data)) {
  6. $show_data=$data ? 'true' : 'false';
  7. }elseif (is_null($data)) {
  8. $show_data='null';
  9. }else{
  10. $show_data=print_r($data,true);
  11. }
  12. $str.=$show_data;
  13. $str.='</pre>';
  14. echo $str;
  15. }

复制代码


/**

* 删除指定的标签和内容
* @param array $tags 需要删除的标签数组
* @param string $str 数据源
* @param string $content 是否删除标签内的内容 0保留内容 1不保留内容
* @return string
*/

  1. function strip_html_tags($tags,$str,$content=0){
  2. if($content){
  3. $html=array();
  4. foreach ($tags as $tag) {
  5. $html[]='/([\s|\S]*?)/';
  6. }
  7. $data=preg_replace($html,'',$str);
  8. }else{
  9. $html=array();
  10. foreach ($tags as $tag) {
  11. $html[]="/(]*>)/i";
  12. }
  13. $data=preg_replace($html, '', $str);
  14. }
  15. return $data;
  16. }

复制代码


/**

* 传递ueditor生成的内容获取其中图片的路径
* @param string $str 含有图片链接的字符串
* @return array 匹配的图片数组
*/

  1. function get_ueditor_image_path($str){
  2. //$preg='/\/Upload\/zhuanti\/u(m)?editor\/\d*\/\d*\.[jpg|jpeg|png|bmp]*/i';
  3. $preg='';
  4. preg_match_all($preg, $str,$data);
  5. return current($data);
  6. }

复制代码


/**

* 字符串截取,支持中文和其他编码
* @param string $str 需要转换的字符串
* @param string $start 开始位置
* @param string $length 截取长度
* @param string $suffix 截断显示字符
* @param string $charset 编码格式
* @return string
*/

  1. function re_substr($str, $start=0, $length, $suffix=true, $charset="utf-8") {
  2. if(function_exists("mb_substr"))
  3. $slice = mb_substr($str, $start, $length, $charset);
  4. elseif(function_exists('iconv_substr')) {
  5. $slice = iconv_substr($str,$start,$length,$charset);
  6. }else{
  7. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  8. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  9. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  10. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  11. preg_match_all($re[$charset], $str, $match);
  12. $slice = join("",array_slice($match[0], $start, $length));
  13. }
  14. $omit=mb_strlen($str) >=$length ? '...' : '';
  15. return $suffix ? $slice.$omit : $slice;
  16. }

复制代码


/**

* 设置验证码,生成验证码字符串
* thinkphp自带验证码生成类
* @return 返回生成的验证码字符串
*/

  1. function show_verify($config=''){
  2. if($config==''){
  3. $config=array(
  4. 'codeSet'=>'1234567890',
  5. 'fontSize'=>30,
  6. 'useCurve'=>false,
  7. 'imageH'=>60,
  8. 'imageW'=>240,
  9. 'length'=>4,
  10. 'fontttf'=>'4.ttf',
  11. );
  12. }
  13. $verify=new \Think\Verify($config);
  14. return $verify->entry();
  15. }

复制代码



/**

* 取得根域名
* @param type $domain 域名
* @return string 返回根域名
*/

  1. function get_url_to_domain($domain) {
  2. $re_domain = '';
  3. $domain_postfix_cn_array = array("com", "net", "org", "gov", "edu", "com.cn", "cn");
  4. $array_domain = explode(".", $domain);
  5. $array_num = count($array_domain) - 1;
  6. if ($array_domain[$array_num] == 'cn') {
  7. if (in_array($array_domain[$array_num - 1], $domain_postfix_cn_array)) {
  8. $re_domain = $array_domain[$array_num - 2] . "." . $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
  9. } else {
  10. $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
  11. }
  12. } else {
  13. $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
  14. }
  15. return $re_domain;
  16. }

复制代码


/**

* 按符号截取字符串的指定部分
* @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
*/

  1. function cut_str($str,$sign,$number){
  2. $array=explode($sign, $str);
  3. $length=count($array);
  4. if($number$length){
  5. return 'error';
  6. }else{
  7. return $new_array[$abs_number-1];
  8. }
  9. }else{
  10. if($number>=$length){
  11. return 'error';
  12. }else{
  13. return $array[$number];
  14. }
  15. }
  16. }

复制代码



/**

* 获取一定范围内的随机数字
* 跟rand()函数的区别是 位数不足补零 例如
* rand(1,9999)可能会得到 465
* rand_number(1,9999)可能会得到 0465 保证是4位的
* @param integer $min 最小值
* @param integer $max 最大值
* @return string
*/

  1. function rand_number ($min=1, $max=9999) {
  2. return sprintf("%0".strlen($max)."d", mt_rand($min,$max));
  3. }

复制代码


/**

* 生成一定数量的随机数,并且不重复
* @param integer $number 数量
* @param string $len 长度
* @param string $type 字串类型
* 0 字母 1 数字 其它 混合
* @return string
*/

  1. function build_count_rand ($number,$length=4,$mode=1) {
  2. 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)
  3. ->order($order)
  4. ->limit($page->firstRow.','.$page->listRows)
  5. ->select();
  6. $data=array(
  7. 'data'=>$list,
  8. 'page'=>$page->show()
  9. );
  10. return $data;
  11. }
  12. /**
  13. * 使用curl获取远程数据
  14. * @param string $url url连接
  15. * @return string 获取到的数据
  16. */
  17. [code]
  18. function curl_get_contents($url){
  19. $ch=curl_init();
  20. curl_setopt($ch, CURLOPT_URL, $url); //设置访问的url地址
  21. //curl_setopt($ch,CURLOPT_HEADER,1); //是否显示头部信息
  22. curl_setopt($ch, CURLOPT_TIMEOUT, 5); //设置超时
  23. curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_); //用户访问代理 User-Agent
  24. curl_setopt($ch, CURLOPT_REFERER,_REFERER_); //设置 referer
  25. curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); //跟踪301
  26. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回结果
  27. $r=curl_exec($ch);
  28. curl_close($ch);
  29. return $r;
  30. }
  31. /*
  32. * 计算星座的函数 string get_zodiac_sign(string month, string day)
  33. * 输入:月份,日期
  34. * 输出:星座名称或者错误信息
  35. * 自学php博客www.zixuephp.cn整理
  36. */
  37. [code]
  38. function get_zodiac_sign($month, $day)
  39. {
  40. // 检查参数有效性
  41. if ($month 12 || $day 31)
  42. return (false);
  43. // 星座名称以及开始日期
  44. $signs = array(
  45. array( "20" => "水瓶座"),
  46. array( "19" => "双鱼座"),
  47. array( "21" => "白羊座"),
  48. array( "20" => "金牛座"),
  49. array( "21" => "双子座"),
  50. array( "22" => "巨蟹座"),
  51. array( "23" => "狮子座"),
  52. array( "23" => "处女座"),
  53. array( "23" => "天秤座"),
  54. array( "24" => "天蝎座"),
  55. array( "22" => "射手座"),
  56. array( "22" => "摩羯座")
  57. );
  58. list($sign_start, $sign_name) = each($signs[(int)$month-1]);
  59. if ($day < $sign_start)
  60. list($sign_start, $sign_name) = each($signs[($month -2 setAccount($accountSid,$accountToken);
  61. $rest->setAppId($appId);
  62. // 发送模板短信
  63. $result=$rest->sendTemplateSMS($phone,array($code,5),$templateId);
  64. if($result==NULL) {
  65. return false;
  66. }
  67. if($result->statusCode!=0) {
  68. return false;
  69. }else{
  70. return true;
  71. }
  72. }

复制代码


/**

* 将路径转换加密
* @param string $file_path 路径
* @return string 转换后的路径
*/

  1. function path_encode($file_path){
  2. return rawurlencode(base64_encode($file_path));
  3. }

复制代码


/**

* 将路径解密
* @param string $file_path 加密后的字符串
* @return string 解密后的路径
*/

  1. function path_decode($file_path){
  2. return base64_decode(rawurldecode($file_path));
  3. }

复制代码


/**

* 根据文件后缀的不同返回不同的结果
* @param string $str 需要判断的文件名或者文件的id
* @return integer 1:图片 2:视频 3:压缩文件 4:文档 5:其他
*/

  1. function file_category($str){
  2. // 取文件后缀名
  3. $str=strtolower(pathinfo($str, PATHINFO_EXTENSION));
  4. // 图片格式
  5. $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');
  6. // 视频格式
  7. $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');
  8. // 压缩格式
  9. $zip=array('rar','zip','tar','cab','uue','jar','iso','z','7-zip','ace','lzh','arj','gzip','bz2','tz');
  10. // 文档格式
  11. $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');
  12. // 匹配不同的结果
  13. switch ($str) {
  14. case in_array($str, $images):
  15. return 1;
  16. break;
  17. case in_array($str, $video):
  18. return 2;
  19. break;
  20. case in_array($str, $zip):
  21. return 3;
  22. break;
  23. case in_array($str, $document):
  24. return 4;
  25. break;
  26. default:
  27. return 5;
  28. break;
  29. }
  30. }

复制代码


/**

* 组合缩略图
* @param string $file_path 原图path
* @param integer $size 比例
* @return string 缩略图
*/

  1. function get_min_image_path($file_path,$width=170,$height=170){
  2. $min_path=str_replace('.', '_'.$width.'_'.$height.'.', trim($file_path,'.'));
  3. $min_path='http://xueba17.oss-cn-beijing.aliyuncs.com'.$min_path;
  4. return $min_path;
  5. }

复制代码


/**

* 不区分大小写的in_array()
* @param string $str 检测的字符
* @param array $array 数组
* @return boolear 是否in_array
*/

  1. function in_iarray($str,$array){
  2. $str=strtolower($str);
  3. $array=array_map('strtolower', $array);
  4. if (in_array($str, $array)) {
  5. return true;
  6. }
  7. return false;
  8. }

复制代码


/**

* 传入时间戳,计算距离现在的时间
* @param number $time 时间戳
* @return string 返回多少以前
*/

  1. function word_time($time) {
  2. $time = (int) substr($time, 0, 10);
  3. $int = time() - $time;
  4. $str = '';
  5. if ($int <= 2){
  6. $str = sprintf('刚刚', $int);
  7. }elseif ($int < 60){
  8. $str = sprintf('%d秒前', $int);
  9. }elseif ($int < 3600){
  10. $str = sprintf('%d分钟前', floor($int / 60));
  11. }elseif ($int open($image_path);
  12. // 生成一个居中裁剪为$width*$height的缩略图并保存
  13. $image->thumb($width, $height,\Think\Image::IMAGE_THUMB_CENTER)->save($min_path);
  14. oss_upload($min_path);
  15. return $min_path;
  16. }

复制代码



/**

* 把用户输入的文本转义(主要针对特殊符号和emoji表情)
*/

  1. function emoji_encode($str){
  2. if(!is_string($str))return $str;
  3. if(!$str || $str=='undefined')return '';
  4. $text = json_encode($str); //暴露出unicode
  5. $text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
  6. return addslashes($str[0]);
  7. },$text); //将emoji的unicode留下,其他不动,这里的正则比原答案增加了d,因为我发现我很多emoji实际上是\ud开头的,反而暂时没发现有\ue开头。
  8. return json_decode($text);
  9. }

复制代码


/**

* 检测是否是手机访问
*/

  1. function is_mobile(){
  2. $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
  3. $useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';
  4. [code]
  5. function _is_mobile($substrs,$text){
  6. foreach($substrs as $substr)
  7. if(false!==strpos($text,$substr)){
  8. return true;
  9. }
  10. return false;
  11. }
  12. $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');
  13. $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');
  14. $found_mobile=_is_mobile($mobile_os_list,$useragent_commentsblock) ||
  15. _is_mobile($mobile_token_list,$useragent);
  16. if ($found_mobile){
  17. return true;
  18. }else{
  19. return false;
  20. }
  21. }

复制代码


/**

* 将utf-16的emoji表情转为utf8文字形
* @param string $str 需要转的字符串
* @return string 转完成后的字符串
*/

  1. function escape_sequence_decode($str) {
  2. $regex = '/\\\u([dD][89abAB][\da-fA-F]{2})\\\u([dD][c-fC-F][\da-fA-F]{2})|\\\u([\da-fA-F]{4})/sx';
  3. return preg_replace_callback($regex, function($matches) {
  4. if (isset($matches[3])) {
  5. $cp = hexdec($matches[3]);
  6. } else {
  7. $lead = hexdec($matches[1]);
  8. $trail = hexdec($matches[2]);
  9. $cp = ($lead << 10) + $trail + 0x10000 - (0xD800 < 0xD7FF && 0xE000 > $cp) {
  10. $cp = 0xFFFD;
  11. }
  12. if ($cp < 0x80) {
  13. return chr($cp);
  14. } else if ($cp > 6).chr(0x80 | $cp & 0x3F);
  15. }
  16. $result = html_entity_decode('&#'.$cp.';');
  17. return $result;
  18. }, $str);
  19. }

复制代码


/**

* 获取当前访问的设备类型
* @return integer 1:其他 2:iOS 3:Android
*/

  1. function get_device_type(){
  2. //全部变成小写字母
  3. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  4. $type = 1;
  5. //分别进行判断
  6. if(strpos($agent, 'iphone')!==false || strpos($agent, 'ipad')!==false){
  7. $type = 2;
  8. }
  9. if(strpos($agent, 'android')!==false){
  10. $type = 3;
  11. }
  12. return $type;
  13. }

复制代码


/**

* 生成pdf
* @param string $html 需要生成的内容
*/

  1. function pdf($html='hello word'){
  2. vendor('Tcpdf.tcpdf');
  3. $pdf = new \Tcpdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4. // 设置打印模式
  5. $pdf->SetCreator(PDF_CREATOR);
  6. $pdf->SetAuthor('Nicola Asuni');
  7. $pdf->SetTitle('TCPDF Example 001');
  8. $pdf->SetSubject('TCPDF Tutorial');
  9. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  10. // 是否显示页眉
  11. $pdf->setPrintHeader(false);
  12. // 设置页眉显示的内容
  13. $pdf->SetHeaderData('logo.png', 60, 'baijunyao.com', '白俊遥博客', array(0,64,255), array(0,64,128));
  14. // 设置页眉字体
  15. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  16. // 页眉距离顶部的距离
  17. $pdf->SetHeaderMargin('5');
  18. // 是否显示页脚
  19. $pdf->setPrintFooter(true);
  20. // 设置页脚显示的内容
  21. $pdf->setFooterData(array(0,64,0), array(0,64,128));
  22. // 设置页脚的字体
  23. $pdf->setFooterFont(Array('dejavusans', '', '10'));
  24. // 设置页脚距离底部的距离
  25. $pdf->SetFooterMargin('10');
  26. // 设置默认等宽字体
  27. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  28. // 设置行高
  29. $pdf->setCellHeightRatio(1);
  30. // 设置左、上、右的间距
  31. $pdf->SetMargins('10', '10', '10');
  32. // 设置是否自动分页 距离底部多少距离时分页
  33. $pdf->SetAutoPageBreak(TRUE, '15');
  34. // 设置图像比例因子
  35. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  36. if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
  37. require_once(dirname(__FILE__).'/lang/eng.php');
  38. $pdf->setLanguageArray($l);
  39. }
  40. $pdf->setFontSubsetting(true);
  41. $pdf->AddPage();
  42. // 设置字体
  43. $pdf->SetFont('stsongstdlight', '', 14, '', true);
  44. $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
  45. $pdf->Output('example_001.pdf', 'I');
  46. }

复制代码


/**

* 生成二维码
* @param string $url url连接
* @param integer $size 尺寸 纯数字
*/

  1. function qrcode($url,$size=4){
  2. Vendor('Phpqrcode.phpqrcode');
  3. QRcode::png($url,false,QR_ECLEVEL_L,$size,2,false,0xFFFFFF,0x000000);
  4. }

复制代码


/**

* 数组转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),
);
*/

  1. function create_xls($data,$filename='simple.xls'){
  2. ini_set('max_execution_time', '0');
  3. Vendor('PHPExcel.PHPExcel');
  4. $filename=str_replace('.xls', '', $filename).'.xls';
  5. $phpexcel = new PHPExcel();
  6. $phpexcel->getProperties()
  7. ->setCreator("Maarten Balliauw")
  8. ->setLastModifiedBy("Maarten Balliauw")
  9. ->setTitle("Office 2007 XLSX Test Document")
  10. ->setSubject("Office 2007 XLSX Test Document")
  11. ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
  12. ->setKeywords("office 2007 openxml php")
  13. ->setCategory("Test result file");
  14. $phpexcel->getActiveSheet()->fromArray($data);
  15. $phpexcel->getActiveSheet()->setTitle('Sheet1');
  16. $phpexcel->setActiveSheetIndex(0);
  17. header('Content-Type: application/vnd.ms-excel');
  18. header("Content-Disposition: attachment;filename=$filename");
  19. header('Cache-Control: max-age=0');
  20. header('Cache-Control: max-age=1');
  21. header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  22. header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  23. header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  24. header ('Pragma: public'); // HTTP/1.0
  25. $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
  26. $objwriter->save('php://output');
  27. exit;
  28. }

复制代码


/**

* 数据转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'
);
*/

  1. function create_csv($data,$filename='simple.csv'){
  2. // 防止没有添加文件后缀
  3. $filename=str_replace('.csv', '', $filename).'.csv';
  4. Header( "Content-type: application/octet-stream ");
  5. Header( "Accept-Ranges: bytes ");
  6. Header( "Content-Disposition: attachment; filename=".$filename);
  7. foreach( $data as $k => $v){
  8. // 替换掉换行
  9. $v=preg_replace('/\s*/', '', $v);
  10. // 转成gbk以兼容office乱码的问题
  11. echo iconv('UTF-8','GBK',$v)."\r\n";
  12. }
  13. }

复制代码



/**

* 判断当前服务器系统
* @return string
*/

  1. function getOS(){
  2. if(PATH_SEPARATOR == ':'){
  3. return 'Linux';
  4. }else{
  5. return 'Windows';
  6. }
  7. }

复制代码


/**

* 当前微妙数
* @return number
*/

  1. function microtime_float() {
  2. list ( $usec, $sec ) = explode ( " ", microtime () );
  3. return (( float ) $usec + ( float ) $sec);
  4. }

复制代码


/**

* 遍历文件夹
* @param string $dir
* @param boolean $all true表示递归遍历
* @return array
*/

  1. function scanfDir($dir='', $all = false, &$ret = array()){
  2. if ( false !== ($handle = opendir ( $dir ))) {
  3. while ( false !== ($file = readdir ( $handle )) ) {
  4. if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) {
  5. $cur_path = $dir . '/' . $file;
  6. if (is_dir ( $cur_path )) {
  7. $ret['dirs'][] =$cur_path;
  8. $all && self::scanfDir( $cur_path, $all, $ret);
  9. } else {
  10. $ret ['files'] [] = $cur_path;
  11. }
  12. }
  13. }
  14. closedir ( $handle );
  15. }
  16. return $ret;
  17. }

复制代码


/**

* 判断字符串是utf-8 还是gb2312
* @param unknown $str
* @param string $default
* @return string
*/

  1. function utf8_gb2312($str, $default = 'gb2312')
  2. {
  3. $str = preg_replace("/[\x01-\x7F]+/", "", $str);
  4. if (empty($str)) return $default;
  5. $preg = array(
  6. "gb2312" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正则判断是否是gb2312
  7. "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u", //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了
  8. );
  9. if ($default == 'gb2312') {
  10. $option = 'utf-8';
  11. } else {
  12. $option = 'gb2312';
  13. }
  14. if (!preg_match($preg[$default], $str)) {
  15. return $option;
  16. }
  17. $str = @iconv($default, $option, $str);
  18. //不能转成 $option, 说明原来的不是 $default
  19. if (empty($str)) {
  20. return $option;
  21. }
  22. return $default;
  23. }

复制代码


/**

* utf-8和gb2312自动转化
* @param unknown $string
* @param string $outEncoding
* @return unknown|string
*/

  1. function safeEncoding($string,$outEncoding = 'UTF-8')
  2. {
  3. $encoding = "UTF-8";
  4. for($i = 0; $i < strlen ( $string ); $i ++) {
  5. if (ord ( $string {$i} ) $v){
  6. $ret[$k] = $v[$key];
  7. }
  8. return $ret;
  9. }

复制代码


/**

* 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数)
* @param string $file 文件/目录
* @return boolean
*/

  1. function is_writeable($file) {
  2. if (is_dir($file)){
  3. $dir = $file;
  4. if ($fp = @fopen("$dir/test.txt", 'w')) {
  5. @fclose($fp);
  6. @unlink("$dir/test.txt");
  7. $writeable = 1;
  8. } else {
  9. $writeable = 0;
  10. }
  11. } else {
  12. if ($fp = @fopen($file, 'a+')) {
  13. @fclose($fp);
  14. $writeable = 1;
  15. } else {
  16. $writeable = 0;
  17. }
  18. }
  19. return $writeable;
  20. }

复制代码


/**

* 格式化单位
*/

  1. function byteFormat( $size, $dec = 2 ) {
  2. $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );
  3. $pos = 0;
  4. while ( $size >= 1024 ) {
  5. $size /= 1024;
  6. $pos ++;
  7. }
  8. return round( $size, $dec ) . " " . $a[$pos];
  9. }

复制代码


/**

* 下拉框,单选按钮 自动选择
* @param $string 输入字符
* @param $param 条件
* @param $type 类型
* selected checked
* @return string
*/

  1. function selected( $string, $param = 1, $type = 'select' ) {
  2. $true = false;
  3. if ( is_array( $param ) ) {
  4. $true = in_array( $string, $param );
  5. }elseif ( $string == $param ) {
  6. $true = true;
  7. }
  8. $return='';
  9. if ( $true )
  10. $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';
  11. echo $return;
  12. }

复制代码


/**

* 下载远程图片
* @param string $url 图片的绝对url
* @param string $filepath 文件的完整路径(例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名
* @param string $filename 要保存的文件名(不含扩展名)
* @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false
*/

  1. function downloadImage($url, $filepath, $filename) {
  2. //服务器返回的头信息
  3. $responseHeaders = array();
  4. //原始图片名
  5. $originalfilename = '';
  6. //图片的后缀名
  7. $ext = '';
  8. $ch = curl_init($url);
  9. //设置curl_exec返回的值包含Http头
  10. curl_setopt($ch, CURLOPT_HEADER, 1);
  11. //设置curl_exec返回的值包含Http内容
  12. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  13. //设置抓取跳转(http 301,302)后的页面
  14. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  15. //设置最多的HTTP重定向的数量
  16. curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
  17. //服务器返回的数据(包括http头信息和内容)
  18. $html = curl_exec($ch);
  19. //获取此次抓取的相关信息
  20. $httpinfo = curl_getinfo($ch);
  21. curl_close($ch);
  22. if ($html !== false) {
  23. //分离response的header和body,由于服务器可能使用了302跳转,所以此处需要将字符串分离为 2+跳转次数 个子串
  24. $httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);
  25. //倒数第二段是服务器最后一次response的http头
  26. $header = $httpArr[count($httpArr) - 2];
  27. //倒数第一段是服务器最后一次response的内容
  28. $body = $httpArr[count($httpArr) - 1];
  29. $header.="\r\n";
  30. //获取最后一次response的header信息
  31. preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);
  32. if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) {
  33. for ($i = 0; $i < count($matches[1]); $i++) {
  34. if (array_key_exists($i, $matches[2])) {
  35. $responseHeaders[$matches[1][$i]] = $matches[2][$i];
  36. }
  37. }
  38. }
  39. //获取图片后缀名
  40. if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {
  41. $originalfilename = $matches[0];
  42. $ext = $matches[1];
  43. } else {
  44. if (array_key_exists('Content-Type', $responseHeaders)) {
  45. if (0 realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));
  46. }
  47. }
  48. }
  49. }
  50. return false;
  51. }

复制代码


/**

* 查找ip是否在某个段位里面
* @param string $ip 要查询的ip
* @param $arrIP 禁止的ip
* @return boolean
*/

  1. function ipAccess($ip='0.0.0.0', $arrIP = array()){
  2. $access = true;
  3. $ip && $arr_cur_ip = explode('.', $ip);
  4. foreach((array)$arrIP as $key=> $value){
  5. if($value == '*.*.*.*'){
  6. $access = false; //禁止所有
  7. break;
  8. }
  9. $tmp_arr = explode('.', $value);
  10. if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) {
  11. //前两段相同
  12. if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){
  13. //第三段为* 或者相同
  14. if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){
  15. //第四段为* 或者相同
  16. $access = false; //在禁止ip列,则禁止访问
  17. break;
  18. }
  19. }
  20. }
  21. }
  22. return $access;
  23. }

复制代码


/**

* @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 为空
*/

  1. function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {
  2. $ckey_length = 4;
  3. // 随机密钥长度 取值 0-32;
  4. // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。
  5. // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方
  6. // 当此值为 0 时,则不产生随机密钥
  7. $key = md5 ( $key ? $key : 'key' ); //这里可以填写默认key值
  8. $keya = md5 ( substr ( $key, 0, 16 ) );
  9. $keyb = md5 ( substr ( $key, 16, 16 ) );
  10. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';
  11. $cryptkey = $keya . md5 ( $keya . $keyc );
  12. $key_length = strlen ( $cryptkey );
  13. $string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
  14. $string_length = strlen ( $string );
  15. $result = '';
  16. $box = range ( 0, 255 );
  17. $rndkey = array ();
  18. for($i = 0; $i <= 255; $i ++) {
  19. $rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
  20. }
  21. for($j = $i = 0; $i < 256; $i ++) {
  22. $j = ($j + $box [$i] + $rndkey [$i]) % 256;
  23. $tmp = $box [$i];
  24. $box [$i] = $box [$j];
  25. $box [$j] = $tmp;
  26. }
  27. for($a = $j = $i = 0; $i 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
  28. return substr ( $result, 26 );
  29. } else {
  30. return '';
  31. }
  32. } else {
  33. return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
  34. }
  35. }

复制代码


/**

* gbk转utf-8格式方法
*/

  1. function gbkToUtf8($str){
  2. return iconv("GBK", "UTF-8", $str);
  3. }

复制代码


/**

* 取得输入目录所包含的所有目录和文件
* 以关联数组形式返回
* author: flynetcn
*/

  1. function deepScanDir($dir)
  2. {
  3. $fileArr = array();
  4. $dirArr = array();
  5. $dir = rtrim($dir, '//');
  6. if(is_dir($dir)){
  7. $dirHandle = opendir($dir);
  8. while(false !== ($fileName = readdir($dirHandle))){
  9. $subFile = $dir . DIRECTORY_SEPARATOR . $fileName;
  10. if(is_file($subFile)){
  11. $fileArr[] = $subFile;
  12. } elseif (is_dir($subFile) && str_replace('.', '', $fileName)!=''){
  13. $dirArr[] = $subFile;
  14. $arr = self::deepScanDir($subFile);
  15. $dirArr = array_merge($dirArr, $arr['dir']);
  16. $fileArr = array_merge($fileArr, $arr['file']);
  17. }
  18. }
  19. closedir($dirHandle);
  20. }
  21. return array('dir'=>$dirArr, 'file'=>$fileArr);
  22. }

复制代码


/**

* 取得输入目录所包含的所有文件
* 以数组形式返回
* author: flynetcn
*/

  1. function get_dir_files($dir)
  2. {
  3. if (is_file($dir)) {
  4. return array($dir);
  5. }
  6. $files = array();
  7. if (is_dir($dir) && ($dir_p = opendir($dir))) {
  8. $ds = DIRECTORY_SEPARATOR;
  9. while (($filename = readdir($dir_p)) !== false) {
  10. if ($filename=='.' || $filename=='..') { continue; }
  11. $filetype = filetype($dir.$ds.$filename);
  12. if ($filetype == 'dir') {
  13. $files = array_merge($files, self::get_dir_files($dir.$ds.$filename));
  14. } elseif ($filetype == 'file') {
  15. $files[] = $dir.$ds.$filename;
  16. }
  17. }
  18. closedir($dir_p);
  19. }
  20. return $files;
  21. }

复制代码


/**

* 删除文件夹及其文件夹下所有文件
*/

  1. function deldir($dir) {
  2. //先删除目录下的文件:
  3. $dh=opendir($dir);
  4. while ($file=readdir($dh)) {
  5. if($file!="." && $file!="..") {
  6. $fullpath=$dir."/".$file;
  7. if(!is_dir($fullpath)) {
  8. unlink($fullpath);
  9. } else {
  10. self::deldir($fullpath);
  11. }
  12. }
  13. }
  14. closedir($dh);
  15. //删除当前文件夹:
  16. if(rmdir($dir)) {
  17. return true;
  18. } else {
  19. return false;
  20. }
  21. }

复制代码



/**

* js 弹窗返回
* @param string $_info
* @return js
*/

  1. function alertBack($_info) {
  2. echo "";
  3. exit();
  4. }

复制代码





/**

* html过滤
* @param array|object $_date
* @return string
*/

  1. function htmlString($_date) {
  2. if (is_array($_date)) {
  3. foreach ($_date as $_key=>$_value) {
  4. $_string[$_key] = self::htmlString($_value); //递归
  5. }
  6. } elseif (is_object($_date)) {
  7. foreach ($_date as $_key=>$_value) {
  8. $_string->$_key = self::htmlString($_value); //递归
  9. }
  10. } else {
  11. $_string = htmlspecialchars($_date);
  12. }
  13. return $_string;
  14. }

复制代码


/**

* 数据库输入过滤
* @param string $_data
* @return string
*/

  1. function mysqlString($_data) {
  2. $_data = trim($_data);
  3. return !GPC ? addcslashes($_data) : $_data;
  4. }

复制代码


/**

* 清理session
*/

  1. function unSession() {
  2. if (session_start()) {
  3. session_destroy();
  4. }
  5. }

复制代码



/**

* 格式化字符串
* @param string $str
* @return string
*/

  1. function formatStr($str) {
  2. $arr = array(' ', ' ', '&', '@', '#', '%', '\'', '"', '\\', '/', '.', ',', '
  3. /**
  4. * 格式化时间
  5. * @param int $time 时间戳
  6. * @return string
  7. */
  8. [code]
  9. function formatDate($time='default') {
  10. $date = $time == 'default' ? date('Y-m-d H:i:s', time()) : date('Y-m-d H:i:s', $time);
  11. return $date;
  12. }

复制代码


/**

* 获得真实IP地址
* @return string
*/

  1. function realIp() {
  2. static $realip = NULL;
  3. if ($realip !== NULL) return $realip;
  4. if (isset($_SERVER)) {
  5. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  6. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  7. foreach ($arr AS $ip) {
  8. $ip = trim($ip);
  9. if ($ip != 'unknown') {
  10. $realip = $ip;
  11. break;
  12. }
  13. }
  14. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  15. $realip = $_SERVER['HTTP_CLIENT_IP'];
  16. } else {
  17. if (isset($_SERVER['REMOTE_ADDR'])) {
  18. $realip = $_SERVER['REMOTE_ADDR'];
  19. } else {
  20. $realip = '0.0.0.0';
  21. }
  22. }
  23. } else {
  24. if (getenv('HTTP_X_FORWARDED_FOR')) {
  25. $realip = getenv('HTTP_X_FORWARDED_FOR');
  26. } elseif (getenv('HTTP_CLIENT_IP')) {
  27. $realip = getenv('HTTP_CLIENT_IP');
  28. } else {
  29. $realip = getenv('REMOTE_ADDR');
  30. }
  31. }
  32. preg_match('/[\d\.]{7,15}/', $realip, $onlineip);
  33. $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
  34. return $realip;
  35. }

复制代码



/**

* 创建目录
* @param string $dir
*/

  1. function createDir($dir) {
  2. if (!is_dir($dir)) {
  3. mkdir($dir, 0777);
  4. }
  5. }

复制代码


/**

* 创建文件(默认为空)
* @param unknown_type $filename
*/

  1. function createFile($filename) {
  2. if (!is_file($filename)) touch($filename);
  3. }

复制代码


/**

* 正确获取变量
* @param string $param
* @param string $type
* @return string
*/

  1. function getData($param, $type='post') {
  2. $type = strtolower($type);
  3. if ($type=='post') {
  4. return self::mysqlString(trim($_POST[$param]));
  5. } elseif ($type=='get') {
  6. return self::mysqlString(trim($_GET[$param]));
  7. }
  8. }

复制代码


/**

* 删除文件
* @param string $filename
*/

  1. function delFile($filename) {
  2. if (file_exists($filename)) unlink($filename);
  3. }

复制代码


/**

* 删除目录
* @param string $path
*/

  1. function delDir($path) {
  2. if (is_dir($path)) rmdir($path);
  3. }

复制代码


/**

* 删除目录及全部子文件
* @param string $dir
* @return bool
*/

  1. function delDirOfAll($dir) {
  2. //先删除目录下的文件:
  3. if (is_dir($dir)) {
  4. $dh=opendir($dir);
  5. while (!!$file=readdir($dh)) {
  6. if($file!="." && $file!="..") {
  7. $fullpath=$dir."/".$file;
  8. if(!is_dir($fullpath)) {
  9. unlink($fullpath);
  10. } else {
  11. self::delDirOfAll($fullpath);
  12. }
  13. }
  14. }
  15. closedir($dh);
  16. //删除当前文件夹:
  17. if(rmdir($dir)) {
  18. return true;
  19. } else {
  20. return false;
  21. }
  22. }
  23. }

复制代码



/**

* 给已经存在的图片添加水印
* @param string $file_path
* @return bool
*/

  1. function addMark($file_path) {
  2. if (file_exists($file_path) && file_exists(MARK)) {
  3. //求出上传图片的名称后缀
  4. $ext_name = strtolower(substr($file_path, strrpos($file_path, '.'), strlen($file_path)));
  5. //$new_name='jzy_' . time() . rand(1000,9999) . $ext_name ;
  6. $store_path = ROOT_PATH . UPDIR;
  7. //求上传图片高宽
  8. $imginfo = getimagesize($file_path);
  9. $width = $imginfo[0];
  10. $height = $imginfo[1];
  11. //添加图片水印
  12. switch($ext_name) {
  13. case '.gif':
  14. $dst_im = imagecreatefromgif($file_path);
  15. break;
  16. case '.jpg':
  17. $dst_im = imagecreatefromjpeg($file_path);
  18. break;
  19. case '.png':
  20. $dst_im = imagecreatefrompng($file_path);
  21. break;
  22. }
  23. $src_im = imagecreatefrompng(MARK);
  24. //求水印图片高宽
  25. $src_imginfo = getimagesize(MARK);
  26. $src_width = $src_imginfo[0];
  27. $src_height = $src_imginfo[1];
  28. //求出水印图片的实际生成位置
  29. $src_x = $width - $src_width - 10;
  30. $src_y = $height - $src_height - 10;
  31. //新建一个真彩色图像
  32. $nimage = imagecreatetruecolor($width, $height);
  33. //拷贝上传图片到真彩图像
  34. imagecopy($nimage, $dst_im, 0, 0, 0, 0, $width, $height);
  35. //按坐标位置拷贝水印图片到真彩图像上
  36. imagecopy($nimage, $src_im, $src_x, $src_y, 0, 0, $src_width, $src_height);
  37. //分情况输出生成后的水印图片
  38. switch($ext_name) {
  39. case '.gif':
  40. imagegif($nimage, $file_path);
  41. break;
  42. case '.jpg':
  43. imagejpeg($nimage, $file_path);
  44. break;
  45. case '.png':
  46. imagepng($nimage, $file_path);
  47. break;
  48. }
  49. //释放资源
  50. imagedestroy($dst_im);
  51. imagedestroy($src_im);
  52. unset($imginfo);
  53. unset($src_imginfo);
  54. //移动生成后的图片
  55. @move_uploaded_file($file_path, ROOT_PATH.UPDIR . $file_path);
  56. }
  57. }

复制代码


/**

* 中文截取2,单字节截取模式
* @access public
* @param string $str 需要截取的字符串
* @param int $slen 截取的长度
* @param int $startdd 开始标记处
* @return string
*/

  1. function cn_substr($str, $slen, $startdd=0){
  2. $cfg_soft_lang = PAGECHARSET;
  3. if($cfg_soft_lang=='utf-8') {
  4. return self::cn_substr_utf8($str, $slen, $startdd);
  5. }
  6. $restr = '';
  7. $c = '';
  8. $str_len = strlen($str);
  9. if($str_len < $startdd+1) {
  10. return '';
  11. }
  12. if($str_len 0x80) {
  13. if($str_len>$i+1) {
  14. $c = $str[$i].$str[$i+1];
  15. }
  16. $i++;
  17. } else {
  18. $c = $str[$i];
  19. }
  20. if($i >= $enddd) {
  21. if(strlen($restr)+strlen($c)>$slen) {
  22. break;
  23. } else {
  24. $restr .= $c;
  25. break;
  26. }
  27. }
  28. }
  29. return $restr;
  30. }

复制代码


/**

* utf-8中文截取,单字节截取模式
* @access public
* @param string $str 需要截取的字符串
* @param int $slen 截取的长度
* @param int $startdd 开始标记处
* @return string
*/

  1. function cn_substr_utf8($str, $length, $start=0) {
  2. if(strlen($str) < $start+1) {
  3. return '';
  4. }
  5. preg_match_all("/./su", $str, $ar);
  6. $str = '';
  7. $tstr = '';
  8. //为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取
  9. for($i=0; isset($ar[0][$i]); $i++) {
  10. if(strlen($tstr) < $start) {
  11. $tstr .= $ar[0][$i];
  12. } else {
  13. if(strlen($str) getOne($db_name, "i.id={$image_id}", "i.path as p, i.big_img as b, i.small_img as s");
  14. foreach ($data as $v) {
  15. @self::delFile(ROOT_PATH . $v['p']);
  16. @self::delFile(ROOT_PATH . $v['b']);
  17. @self::delFile(ROOT_PATH . $v['s']);
  18. }
  19. $m->del(PREFIX . 'images', "id={$image_id}");
  20. unset($m);
  21. }

复制代码

/**

* 图片等比例缩放
* @param resource $im 新建图片资源(imagecreatefromjpeg/imagecreatefrompng/imagecreatefromgif)
* @param int $maxwidth 生成图像宽
* @param int $maxheight 生成图像高
* @param string $name 生成图像名称
* @param string $filetype文件类型(.jpg/.gif/.png)
*/

  1. function resizeImage($im, $maxwidth, $maxheight, $name, $filetype) {
  2. $pic_width = imagesx($im);
  3. $pic_height = imagesy($im);
  4. if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
  5. if($maxwidth && $pic_width>$maxwidth) {
  6. $widthratio = $maxwidth/$pic_width;
  7. $resizewidth_tag = true;
  8. }
  9. if($maxheight && $pic_height>$maxheight) {
  10. $heightratio = $maxheight/$pic_height;
  11. $resizeheight_tag = true;
  12. }
  13. if($resizewidth_tag && $resizeheight_tag) {
  14. if($widthratio0)) {
  15. $file_data = fread($fp, $buffer);
  16. $file_count += $buffer;
  17. echo $file_data;
  18. }
  19. fclose($fp); //关闭文件
  20. }

复制代码




最新回复 (0)
返回
支持中心
邮箱:winkill2012@qqcom
新站优化中!部分功能尚未完善,敬请谅解!
支持中心