funbase-hayden.php Submit("210007","XXXXX","XXXX",$str,$phone);return $code;}/** * 判断用户输入是否存在敏感词 * 需要在ThinkPHP的ORG扩展文件夹中,添加敏感词类文件SensitiveFilter.php *自学php博客www.zixueph
Submit("210007","XXXXX","XXXX",$str,$phone);
return $code;
}
/**
* 判断用户输入是否存在敏感词
* 需要在ThinkPHP的ORG扩展文件夹中,添加敏感词类文件SensitiveFilter.php
*自学php博客www.zixuephp.cn整理
*/
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;
}
/**
*传递数据以易于阅读的样式格式化后输出
*自学php博客www.zixuephp.cn整理
*/
function p($data){
// 定义样式
$str='';
// 如果是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.='';
echo $str;
}
/**
* app 图片上传
* $path 上传图图片的路径
* $maxSize 上传图片的大小控制
* @return string 上传后的图片名
* 自学php博客www.zixuephp.cn整理
*/
function app_upload_image($path,$maxSize=52428800){
ini_set('max_execution_time', '0');
// 去除两边的/
$path=trim($path,'.');
$path=trim($path,'/');
$config=array(
'rootPath' =>'./', //文件上传保存的根路径
'savePath' =>'./'.$path.'/',
'exts' => array('jpg', 'gif', 'png', 'jpeg','bmp'),
'maxSize' => $maxSize,
'autoSub' => true,
);
$upload = new \Think\Upload($config);// 实例化上传类
$info = $upload->upload();
if($info) {
foreach ($info as $k => $v) {
$data[]=trim($v['savepath'],'.').$v['savename'];
}
return $data;
}
}
/**
* 阿里云OSS操作
* 实例化阿里云oos
* @return object 实例化得到的对象
* 自学php博客www.zixuephp.cn整理
*/
function new_oss(){
vendor('Alioss.autoload');
$config=C('ALIOSS_CONFIG');
$oss=new \OSS\OssClient($config['KEY_ID'],$config['KEY_SECRET'],$config['END_POINT']);
return $oss;
}
/**
* 阿里云OSS操作
* 上传Object
* key 用专题的id标识本片专题
* $str 是要上传的专题的内容
* 自学php博客www.zixuephp.cn整理
*/
function uploadObject($str,$id){
$id='M_Upload/zhuanti/content/'.$id;
$accessKeyId=C('ALIOSS_CONFIG.KEY_ID');
$accessKeySecret=C('ALIOSS_CONFIG.KEY_SECRET');
$endpoint=C('ALIOSS_CONFIG.END_POINT');
$bucket=C('ALIOSS_CONFIG.BUCKET');
//$oss->putObject($bucket,$id,$str);
vendor('Alioss.autoload');
$config=C('ALIOSS_CONFIG');
$ossClient=new \OSS\OssClient($config['KEY_ID'],$config['KEY_SECRET'],$config['END_POINT']);
try {
//$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$ossClient->putObject($bucket, $id, $str);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
return $id;
}
/**
* 阿里云OSS操作
* 上传Object
* key 用专题的id标识本片专题
* $str 是要上传的专题的内容
* 自学php博客www.zixuephp.cn整理
*/
function downObject($id){
$accessKeyId=C('ALIOSS_CONFIG.KEY_ID');
$accessKeySecret=C('ALIOSS_CONFIG.KEY_SECRET');
$endpoint=C('ALIOSS_CONFIG.END_POINT');
$bucket=C('ALIOSS_CONFIG.BUCKET');
//$oss->putObject($bucket,$id,$str);
try {
vendor('Alioss.autoload');
$config=C('ALIOSS_CONFIG');
$ossClient=new \OSS\OssClient($config['KEY_ID'],$config['KEY_SECRET'],$config['END_POINT']);
$content=$ossClient->getObject($bucket, $id);
print("object content: " . $content);
} catch (OssException $e) {
print $e->getMessage();
}
}
/**
* 阿里云OSS操作
* 上传文件到阿里云OSS并删除本地文件
* @param string $path 文件路径
* @return bollear 是否上传
* 自学php博客www.zixuephp.cn整理
*/
function oss_upload($path){
// 获取bucket名称
$bucket=C('ALIOSS_CONFIG.BUCKET');
// 先统一去除左侧的.或者/ 再添加./
$oss_path=ltrim($path,'./');
$path='./'.$oss_path;
if (file_exists($path)) {
// 实例化oss类
$oss=new_oss();
// 上传到oss
$oss->uploadFile($bucket,$oss_path,$path);
// 如需上传到oss后 自动删除本地的文件 则删除下面的注释
unlink($path);
return true;
}
return false;
}
/**
* 阿里云OSS操作
* 删除阿里云OSS上指定文件
* @param string $object 文件路径 例如删除 /Public/README.md文件 传Public/README.md 即可
* 自学php博客www.zixuephp.cn整理
*/
function oss_delet_object($object){
// 实例化oss类
$oss=new_oss();
// 获取bucket名称
$bucket=C('ALIOSS_CONFIG.BUCKET');
$test=$oss->deleteObject($bucket,$object);
}
/**
* 阿里云OSS操作
* 获取完整网络连接
* @param string $path 文件路径
* @return string http连接
* 自学php博客www.zixuephp.cn整理
*/
function get_url($path){
// 如果是空;返回空
if (empty($path)) {
return '';
}
// 如果已经有http直接返回
if (strpos($path, 'http://')!==false) {
return $path;
}
// 判断是否使用了oss
$alioss=C('ALIOSS_CONFIG');
if (empty($alioss['KEY_ID'])) {
return 'http://'.$_SERVER['HTTP_HOST'].$path;
}else{
$path=ltrim($path,'.');
return 'http://'.$alioss['BUCKET'].'.'.$alioss['END_POINT'].$path;
}
}
/**
* app 视频上传
* @return string 上传后的视频名
* 自学php博客www.zixuephp.cn整理
*/
function app_upload_video($path,$maxSize=52428800){
ini_set('max_execution_time', '0');
// 去除两边的/
$path=trim($path,'.');
$path=trim($path,'/');
$config=array(
'rootPath' =>'./', //文件上传保存的根路径
'savePath' =>'./'.$path.'/',
'exts' => array('mp4','avi','3gp','rmvb','gif','wmv','mkv','mpg','vob','mov','flv','swf','mp3','ape','wma','aac','mmf','amr','m4a','m4r','ogg','wav','wavpack'),
'maxSize' => $maxSize,
'autoSub' => true,
);
$upload = new \Think\Upload($config);// 实例化上传类
$info = $upload->upload();
if($info) {
foreach ($info as $k => $v) {
$data[]=trim($v['savepath'],'.').$v['savename'];
}
return $data;
}
}
/**
* 返回文件格式
* @param string $str 文件名
* @return string 文件格式
* 自学php博客www.zixuephp.cn整理
*/
function file_format($str){
// 取文件后缀名
$str=strtolower(pathinfo($str, PATHINFO_EXTENSION));
// 图片格式
$image=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');
// 文档格式
$text=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, $image):
return 'image';
break;
case in_array($str, $video):
return 'video';
break;
case in_array($str, $zip):
return 'zip';
break;
case in_array($str, $text):
return 'text';
break;
default:
return 'image';
break;
}
}
/**
* 发送友盟推送消息
* @param integer $uid 用户id
* @param string $title 推送的标题
* @return boolear 是否成功
* 自学php博客www.zixuephp.cn整理
*/
function umeng_push($uid,$title){
// 获取token
$device_tokens=D('OauthUser')->getToken($uid,2);
// 如果没有token说明移动端没有登录;则不发送通知
if (empty($device_tokens)) {
return false;
}
// 导入友盟
Vendor('Umeng.Umeng');
// 自定义字段 根据实际环境分配;如果不用可以忽略
$status=1;
// 消息未读总数统计 根据实际环境获取未读的消息总数 此数量会显示在app图标右上角
$count_number=1;
$data=array(
'key'=>'status',
'value'=>"$status",
'count_number'=>$count_number
);
// 判断device_token 64位表示为苹果 否则为安卓
if(strlen($device_tokens)==64){
$key=C('UMENG_IOS_APP_KEY');
$timestamp=C('UMENG_IOS_SECRET');
$umeng=new \Umeng($key, $timestamp);
$umeng->sendIOSUnicast($data,$title,$device_tokens);
}else{
$key=C('UMENG_ANDROID_APP_KEY');
$timestamp=C('UMENG_ANDROID_SECRET');
$umeng=new \Umeng($key, $timestamp);
$umeng->sendAndroidUnicast($data,$title,$device_tokens);
}
return true;
}
/**
* 返回用户id
* @return integer 用户id
* 自学php博客www.zixuephp.cn整理
*/
function get_uid(){
return $_SESSION['user']['id'];//根据自己登录的时候保存的SESSION元素而定
}
/**
* 返回iso、Android、ajax的json格式数据
* @param array $data 需要发送到前端的数据
* @param string $error_message 成功或者错误的提示语
* @param integer $error_code 状态码: 0:成功 1:失败
* @return string json格式的数据
* 自学php博客www.zixuephp.cn整理
*/
function ajax_return($data='',$error_message='成功',$error_code=1){
$all_data=array(
'error_code'=>$error_code,
'error_message'=>$error_message,
);
if ($data!=='') {
$all_data['data']=$data;
// app 禁止使用和为了统一字段做的判断
$reserved_words=array('id','title','price','product_title','product_id','product_category','product_number');
foreach ($reserved_words as $k => $v) {
if (array_key_exists($v, $data)) {
echo 'app不允许使用【'.$v.'】这个键名 —— 此提示是function.php 中的ajax_return函数返回的';
die;
}
}
}
// 如果是ajax或者app访问;则返回json数据 pc访问直接p出来
echo json_encode($all_data);
exit(0);
}
/**
* 检测是否登录
* @return boolean 是否登录
* 自学php博客www.zixuephp.cn整理
*/
function check_login(){
if (!empty($_SESSION['user']['id'])){
return true;
}else{
return false;
}
}
/**
* 根据配置项获取对应的key和secret
* @return array key和secret
* 自学php博客www.zixuephp.cn整理
*/
function get_rong_key_secret(){
// 判断是需要开发环境还是生产环境的key
if (C('RONG_IS_DEV')) {
$key=C('RONG_DEV_APP_KEY');
$secret=C('RONG_DEV_APP_SECRET');
}else{
$key=C('RONG_PRO_APP_KEY');
$secret=C('RONG_PRO_APP_SECRET');
}
$data=array(
'key'=>$key,
'secret'=>$secret
);
return $data;
}
/**
* 获取融云token
* @param integer $uid 用户id
* @return integer token
* 自学php博客www.zixuephp.cn整理
*/
function get_rongcloud_token($uid){
// 从数据库中获取token
$token=D('OauthUser')->getToken($uid,1);
// 如果有token就返回
if ($token) {
return $token;
}
// 获取用户昵称和头像
$user_data=M('Users')->field('username,avatar')->getById($uid);
// 用户不存在
if (empty($user_data)) {
return false;
}
// 获取头像url格式
$avatar=get_url($user_data['avatar']);
// 获取key和secret
$key_secret=get_rong_key_secret();
// 实例化融云
$rong_cloud=new \Org\Xb\RongCloud($key_secret['key'],$key_secret['secret']);
// 获取token
$token_json=$rong_cloud->getToken($uid,$user_data['username'],$avatar);
$token_array=json_decode($token_json,true);
// 获取token失败
if ($token_array['code']!=200) {
return false;
}
$token=$token_array['token'];
$data=array(
'uid'=>$uid,
'type'=>1,
'nickname'=>$user_data['username'],
'head_img'=>$avatar,
'access_token'=>$token
);
// 插入数据库
$result=D('OauthUser')->addData($data);
if ($result) {
return $token;
}else{
return false;
}
}
/**
* 更新融云头像
* @param integer $uid 用户id
* @return boolear 操作是否成功
* 自学php博客www.zixuephp.cn整理
*/
function refresh_rongcloud_token($uid){
// 获取用户昵称和头像
$user_data=M('Users')->field('username,avatar')->getById($uid);
// 用户不存在
if (empty($user_data)) {
return false;
}
$avatar=get_url($user_data['avatar']);
// 获取key和secret
$key_secret=get_rong_key_secret();
// 实例化融云
$rong_cloud=new \Org\Xb\RongCloud($key_secret['key'],$key_secret['secret']);
// 更新融云用户头像
$result_json=$rong_cloud->userRefresh($uid,$user_data['username'],$avatar);
$result_array=json_decode($result_json,true);
if ($result_array['code']==200) {
return true;
}else{
return false;
}
}
/**
* 删除指定的标签和内容
* @param array $tags 需要删除的标签数组
* @param string $str 数据源
* @param string $content 是否删除标签内的内容 0保留内容 1不保留内容
* @return string
* 自学php博客www.zixuephp.cn整理
*/
function strip_html_tags($tags,$str,$content=0){
if($content){
$html=array();
foreach ($tags as $tag) {
$html[]='/(<'.$tag.'.*?>[\s|\S]*?<\/'.$tag.'>)/';
}
$data=preg_replace($html,'',$str);
}else{
$html=array();
foreach ($tags as $tag) {
$html[]="/(<(?:\/".$tag."|".$tag.")[^>]*>)/i";
}
$data=preg_replace($html, '', $str);
}
return $data;
}
/**
* 传递ueditor生成的内容获取其中图片的路径
* @param string $str 含有图片链接的字符串
* @return array 匹配的图片数组
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
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 返回生成的验证码字符串
* 自学php博客www.zixuephp.cn整理
*/
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();
}
/**
* thinkphp自带验证码检测功能
* 自学php博客www.zixuephp.cn整理
*/
function check_verify($code){
$verify=new \Think\Verify();
return $verify->check($code);
}
/**
* 取得根域名
* @param type $domain 域名
* @return string 返回根域名
* 自学php博客www.zixuephp.cn整理
*/
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 返回截取的内容
* 自学php博客www.zixuephp.cn整理
*/
/* 示例
$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<0){
$new_array=array_reverse($array);
$abs_number=abs($number);
if($abs_number>$length){
return 'error';
}else{
return $new_array[$abs_number-1];
}
}else{
if($number>=$length){
return 'error';
}else{
return $array[$number];
}
}
}
/**
* 发送邮件
* @param string $address 需要发送的邮箱地址 发送给多个地址需要写成数组形式
* @param string $subject 标题
* @param string $content 内容
* @return boolean 是否成功
* 自学php博客www.zixuephp.cn整理
*/
function send_email($address,$subject,$content){
$email_smtp=C('EMAIL_SMTP');
$email_username=C('EMAIL_USERNAME');
$email_password=C('EMAIL_PASSWORD');
$email_from_name=C('EMAIL_FROM_NAME');
if(empty($email_smtp) || empty($email_username) || empty($email_password) || empty($email_from_name)){
return array("error"=>1,"message"=>'邮箱配置不完整');
}
require './ThinkPHP/Library/Org/Nx/class.phpmailer.php';
require './ThinkPHP/Library/Org/Nx/class.smtp.php';
$phpmailer=new \Phpmailer();
// 设置PHPMailer使用SMTP服务器发送Email
$phpmailer->IsSMTP();
// 设置为html格式
$phpmailer->IsHTML(true);
// 设置邮件的字符编码'
$phpmailer->CharSet='UTF-8';
// 设置SMTP服务器。
$phpmailer->Host=$email_smtp;
// 设置为"需要验证"
$phpmailer->SMTPAuth=true;
// 设置用户名
$phpmailer->Username=$email_username;
// 设置密码
$phpmailer->Password=$email_password;
// 设置邮件头的From字段。
$phpmailer->From=$email_username;
// 设置发件人名字
$phpmailer->FromName=$email_from_name;
// 添加收件人地址,可以多次使用来添加多个收件人
if(is_array($address)){
foreach($address as $addressv){
$phpmailer->AddAddress($addressv);
}
}else{
$phpmailer->AddAddress($address);
}
// 设置邮件标题
$phpmailer->Subject=$subject;
// 设置邮件正文
$phpmailer->Body=$content;
// 发送邮件。
if(!$phpmailer->Send()) {
$phpmailererror=$phpmailer->ErrorInfo;
return array("error"=>1,"message"=>$phpmailererror);
}else{
return array("error"=>0);
}
}
/**
* 获取一定范围内的随机数字
* 跟rand()函数的区别是 位数不足补零 例如
* rand(1,9999)可能会得到 465
* rand_number(1,9999)可能会得到 0465 保证是4位的
* @param integer $min 最小值
* @param integer $max 最大值
* @return string
* 自学php博客www.zixuephp.cn整理
*/
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
where($map)
->count();
$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;
}
/*
* @param string $path 字符串 保存文件路径示例: /Upload/image/
* @param string $format 文件格式限制
* @param integer $maxSize 允许的上传文件最大值 52428800
* @return booler 返回ajax的json格式数据
* 自学php博客www.zixuephp.cn整理
*/
function post_upload($path='file',$format='empty',$maxSize='52428800'){
ini_set('max_execution_time', '0');
// 去除两边的/
$path=trim($path,'/');
// 添加Upload根目录
$path=strtolower(substr($path, 0,6))==='upload' ? ucfirst($path) : 'Upload/'.$path;
// 上传文件类型控制
$ext_arr= array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'photo' => array('jpg', 'jpeg', 'png'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
);
if(!empty($_FILES)){
// 上传文件配置
$config=array(
'maxSize' => $maxSize, // 上传文件最大为50M
'rootPath' => './', //文件上传保存的根路径
'savePath' => './'.$path.'/', //文件上传的保存路径(相对于根路径)
'saveName' => array('uniqid',''), //上传文件的保存规则,支持数组和字符串方式定义
'autoSub' => true, // 自动使用子目录保存上传文件 默认为true
'exts' => isset($ext_arr[$format])?$ext_arr[$format]:'',
);
// 实例化上传
$upload=new \Think\Upload($config);
// 调用上传方法
$info=$upload->upload();
$data=array();
if(!$info){
// 返回错误信息
$error=$upload->getError();
$data['error_info']=$error;
return $data;
}else{
// 返回成功信息
foreach($info as $file){
$data['name']=trim($file['savepath'].$file['savename'],'.');
return $data;
}
}
}
}
/**
* 上传文件类型控制 此方法仅限ajax上传使用
* @param string $path 字符串 保存文件路径示例: /Upload/image/
* @param string $format 文件格式限制
* @param integer $maxSize 允许的上传文件最大值 52428800
* @return booler 返回ajax的json格式数据
* 自学php博客www.zixuephp.cn整理
*/
function upload($path='file',$format='empty',$maxSize='52428800'){
ini_set('max_execution_time', '0');
// 去除两边的/
$path=trim($path,'/');
// 添加Upload根目录
$path=strtolower(substr($path, 0,6))==='upload' ? ucfirst($path) : 'Upload/'.$path;
// 上传文件类型控制
$ext_arr= array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'photo' => array('jpg', 'jpeg', 'png'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
);
if(!empty($_FILES)){
// 上传文件配置
$config=array(
'maxSize' => $maxSize, // 上传文件最大为50M
'rootPath' => './', //文件上传保存的根路径
'savePath' => './'.$path.'/', //文件上传的保存路径(相对于根路径)
'saveName' => array('uniqid',''), //上传文件的保存规则,支持数组和字符串方式定义
'autoSub' => true, // 自动使用子目录保存上传文件 默认为true
'exts' => isset($ext_arr[$format])?$ext_arr[$format]:'',
);
// 实例化上传
$upload=new \Think\Upload($config);
// 调用上传方法
$info=$upload->upload();
$data=array();
if(!$info){
// 返回错误信息
$error=$upload->getError();
$data['error_info']=$error;
echo json_encode($data);
}else{
// 返回成功信息
foreach($info as $file){
$data['name']=trim($file['savepath'].$file['savename'],'.');
echo json_encode($data);
}
}
}
}
/**
* 使用curl获取远程数据
* @param string $url url连接
* @return string 获取到的数据
* 自学php博客www.zixuephp.cn整理
*/
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整理
*/
function get_zodiac_sign($month, $day)
{
// 检查参数有效性
if ($month < 1 || $month > 12 || $day < 1 || $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 < 0) ? $month = 11: $month -= 2]);
return $sign_name;
}
/**
* 发送 容联云通讯 验证码
* @param int $phone 手机号
* @param int $code 验证码
* @return boole 是否发送成功
* 自学php博客www.zixuephp.cn整理
*/
function send_sms_code($phone,$code){
//请求地址,格式如下,不需要写https://
$serverIP='app.cloopen.com';
//请求端口
$serverPort='8883';
//REST版本号
$softVersion='2013-12-26';
//主帐号
$accountSid=C('RONGLIAN_ACCOUNT_SID');
//主帐号Token
$accountToken=C('RONGLIAN_ACCOUNT_TOKEN');
//应用Id
$appId=C('RONGLIAN_APPID');
//应用Id
$templateId=C('RONGLIAN_TEMPLATE_ID');
$rest = new \Org\Xb\Rest($serverIP,$serverPort,$softVersion);
$rest->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 转换后的路径
* 自学php博客www.zixuephp.cn整理
*/
function path_encode($file_path){
return rawurlencode(base64_encode($file_path));
}
/**
* 将路径解密
* @param string $file_path 加密后的字符串
* @return string 解密后的路径
* 自学php博客www.zixuephp.cn整理
*/
function path_decode($file_path){
return base64_decode(rawurldecode($file_path));
}
/**
* 根据文件后缀的不同返回不同的结果
* @param string $str 需要判断的文件名或者文件的id
* @return integer 1:图片 2:视频 3:压缩文件 4:文档 5:其他
* 自学php博客www.zixuephp.cn整理
*/
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 缩略图
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
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 返回多少以前
* 自学php博客www.zixuephp.cn整理
*/
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 < 86400){
$str = sprintf('%d小时前', floor($int / 3600));
}else{
$str = date('Y-m-d H:i:s', $time);
}
return $str;
}
/**
* 生成缩略图
* @param string $image_path 原图path
* @param integer $width 缩略图的宽
* @param integer $height 缩略图的高
* @return string 缩略图path
* 自学php博客www.zixuephp.cn整理
*/
function crop_image($image_path,$width=170,$height=170){
$image_path=trim($image_path,'.');
$min_path='.'.str_replace('.', '_'.$width.'_'.$height.'.', $image_path);
$image = new \Think\Image();
$image->open($image_path);
// 生成一个居中裁剪为$width*$height的缩略图并保存
$image->thumb($width, $height,\Think\Image::IMAGE_THUMB_CENTER)->save($min_path);
oss_upload($min_path);
return $min_path;
}
/**
* 上传文件类型控制 此方法仅限ajax上传使用
* @param string $path 字符串 保存文件路径示例: /Upload/image/
* @param string $format 文件格式限制
* @param integer $maxSize 允许的上传文件最大值 52428800
* @return booler 返回ajax的json格式数据
* 自学php博客www.zixuephp.cn整理
*/
function ajax_upload($path='file',$format='empty',$maxSize='52428800'){
ini_set('max_execution_time', '0');
// 去除两边的/
$path=trim($path,'/');
// 添加Upload根目录
$path=strtolower(substr($path, 0,6))==='upload' ? ucfirst($path) : 'Upload/'.$path;
// 上传文件类型控制
$ext_arr= array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'photo' => array('jpg', 'jpeg', 'png'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
);
if(!empty($_FILES)){
// 上传文件配置
$config=array(
'maxSize' => $maxSize, // 上传文件最大为50M
'rootPath' => './', // 文件上传保存的根路径
'savePath' => './'.$path.'/', // 文件上传的保存路径(相对于根路径)
'saveName' => array('uniqid',''), // 上传文件的保存规则,支持数组和字符串方式定义
'autoSub' => true, // 自动使用子目录保存上传文件 默认为true
'exts' => isset($ext_arr[$format])?$ext_arr[$format]:'',
);
// 实例化上传
$upload=new \Think\Upload($config);
// 调用上传方法
$info=$upload->upload();
$data=array();
if(!$info){
// 返回错误信息
$error=$upload->getError();
$data['error_info']=$error;
echo json_encode($data);
}else{
// 返回成功信息
foreach($info as $file){
$data['name']=trim($file['savepath'].$file['savename'],'.');
echo json_encode($data);
}
}
}
}
/**
* 检测webuploader上传是否成功
* @param string $file_path post中的字段
* @return boolear 是否成功
* 自学php博客www.zixuephp.cn整理
*/
function upload_success($file_path){
// 为兼容传进来的有数组;先转成json
$file_path=json_encode($file_path);
// 如果有undefined说明上传失败
if (strpos($file_path, 'undefined') !== false) {
return false;
}
// 如果没有.符号说明上传失败
if (strpos($file_path, '.') === false) {
return false;
}
// 否则上传成功则返回true
return true;
}
/**
* 把用户输入的文本转义(主要针对特殊符号和emoji表情)
* 自学php博客www.zixuephp.cn整理
*/
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);
}
/**
* 检测是否是手机访问
* 自学php博客www.zixuephp.cn整理
*/
function is_mobile(){
$useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';
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 转完成后的字符串
* 自学php博客www.zixuephp.cn整理
*/
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 << 10) - 0xDC00;
}
if ($cp > 0xD7FF && 0xE000 > $cp) {
$cp = 0xFFFD;
}
if ($cp < 0x80) {
return chr($cp);
} else if ($cp < 0xA0) {
return chr(0xC0 | $cp >> 6).chr(0x80 | $cp & 0x3F);
}
$result = html_entity_decode('&#'.$cp.';');
return $result;
}, $str);
}
/**
* 获取当前访问的设备类型
* @return integer 1:其他 2:iOS 3:Android
* 自学php博客www.zixuephp.cn整理
*/
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 需要生成的内容
* 自学php博客www.zixuephp.cn整理
*/
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 尺寸 纯数字
* 自学php博客www.zixuephp.cn整理
*/
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文件名
* 自学php博客www.zixuephp.cn整理
* 示例数据:
$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'
);
* 自学php博客www.zixuephp.cn整理
*/
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";
}
}
/**
* 跳向支付宝付款
* @param array $order 订单数据 必须包含 out_trade_no(订单号)、price(订单金额)、subject(商品名称标题)
* 自学php博客www.zixuephp.cn整理
*/
function alipay($order){
vendor('Alipay.AlipaySubmit','','.class.php');
// 获取配置
$config=C('ALIPAY_CONFIG');
$data=array(
"_input_charset" => $config['input_charset'], // 编码格式
"logistics_fee" => "0.00", // 物流费用
"logistics_payment" => "SELLER_PAY", // 物流支付方式SELLER_PAY(卖家承担运费)、BUYER_PAY(买家承担运费)
"logistics_type" => "EXPRESS", // 物流类型EXPRESS(快递)、POST(平邮)、EMS(EMS)
"notify_url" => $config['notify_url'], // 异步接收支付状态通知的链接
"out_trade_no" => $order['out_trade_no'], // 订单号
"partner" => $config['partner'], // partner 从支付宝商户版个人中心获取
"payment_type" => "1", // 支付类型对应请求时的 payment_type 参数,原样返回。固定设置为1即可
"price" => $order['price'], // 订单价格单位为元
// "price" => 0.01, // // 调价用于测试
"quantity" => "1", // price、quantity 能代替 total_fee。 即存在 total_fee,就不能存在 price 和 quantity;存在 price、quantity, 就不能存在 total_fee。 (没绕明白;好吧;那无视这个参数即可)
"receive_address" => '1', // 收货人地址 即时到账方式无视此参数即可
"receive_mobile" => '1', // 收货人手机号码 即时到账方式无视即可
"receive_name" => '1', // 收货人姓名 即时到账方式无视即可
"receive_zip" => '1', // 收货人邮编 即时到账方式无视即可
"return_url" => $config['return_url'], // 页面跳转 同步通知 页面路径 支付宝处理完请求后,当前页面自 动跳转到商户网站里指定页面的 http 路径。
"seller_email" => $config['seller_email'], // email 从支付宝商户版个人中心获取
"service" => "create_direct_pay_by_user", // 接口名称 固定设置为create_direct_pay_by_user
"show_url" => $config['show_url'], // 商品展示网址,收银台页面上,商品展示的超链接。
"subject" => $order['subject'] // 商品名称商品的标题/交易标题/订单标 题/订单关键字等
);
$alipay=new \AlipaySubmit($config);
$new=$alipay->buildRequestPara($data);
$go_pay=$alipay->buildRequestForm($new, 'get','支付');
echo $go_pay;
}
/**
* 微信扫码支付
* @param array $order 订单 必须包含支付所需要的参数 body(产品描述)、total_fee(订单金额)、out_trade_no(订单号)、product_id(产品id)
* 自学php博客www.zixuephp.cn整理
*/
function weixinpay($order){
$order['trade_type']='NATIVE';
Vendor('Weixinpay.Weixinpay');
$weixinpay=new \Weixinpay();
$weixinpay->pay($order);
}
/**
* geetest检测验证码
* 自学php博客www.zixuephp.cn整理
*/
function geetest_chcek_verify($data){
$geetest_id=C('GEETEST_ID');
$geetest_key=C('GEETEST_KEY');
$geetest=new \Org\Xb\Geetest($geetest_id,$geetest_key);
$user_id=$_SESSION['geetest']['user_id'];
if ($_SESSION['geetest']['gtserver']==1) {
$result=$geetest->success_validate($data['geetest_challenge'], $data['geetest_validate'], $data['geetest_seccode'], $user_id);
if ($result) {
return true;
} else{
return false;
}
}else{
if ($geetest->fail_validate($data['geetest_challenge'],$data['geetest_validate'],$data['geetest_seccode'])) {
return true;
}else{
return false;
}
}
}
/**
* 判断当前服务器系统
* @return string
* 自学php博客www.zixuephp.cn整理
*/
function getOS(){
if(PATH_SEPARATOR == ':'){
return 'Linux';
}else{
return 'Windows';
}
}
/**
* 当前微妙数
* @return number
* 自学php博客www.zixuephp.cn整理
*/
function microtime_float() {
list ( $usec, $sec ) = explode ( " ", microtime () );
return (( float ) $usec + ( float ) $sec);
}
/**
* 遍历文件夹
* @param string $dir
* @param boolean $all true表示递归遍历
* @return array
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
function safeEncoding($string,$outEncoding = 'UTF-8')
{
$encoding = "UTF-8";
for($i = 0; $i < strlen ( $string ); $i ++) {
if (ord ( $string {$i} ) < 128)
continue;
if ((ord ( $string {$i} ) & 224) == 224) {
// 第一个字节判断通过
$char = $string {++ $i};
if ((ord ( $char ) & 128) == 128) {
// 第二个字节判断通过
$char = $string {++ $i};
if ((ord ( $char ) & 128) == 128) {
$encoding = "UTF-8";
break;
}
}
}
if ((ord ( $string {$i} ) & 192) == 192) {
// 第一个字节判断通过
$char = $string {++ $i};
if ((ord ( $char ) & 128) == 128) {
// 第二个字节判断通过
$encoding = "GB2312";
break;
}
}
}
if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))
return $string;
else
return @iconv ( $encoding, $outEncoding, $string );
}
/**
* 返回二维数组中某个键名的所有值
* @param input $array
* @param string $key
* @return array
* 自学php博客www.zixuephp.cn整理
*/
function array_key_values($array =array(), $key='')
{
$ret = array();
foreach((array)$array as $k=>$v){
$ret[$k] = $v[$key];
}
return $ret;
}
/**
* 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数)
* @param string $file 文件/目录
* @return boolean
* 自学php博客www.zixuephp.cn整理
*/
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;
}
/**
* 格式化单位
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
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 < preg_match('{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) {
$ext = $extmatches[1];
}
}
}
//保存文件
if (!empty($ext)) {
//如果目录不存在,则先要创建目录
if(!is_dir($filepath)){
mkdir($filepath, 0777, true);
}
$filepath .= '/'.$filename.".$ext";
$local_file = fopen($filepath, 'w');
if (false !== $local_file) {
if (false !== fwrite($local_file, $body)) {
fclose($local_file);
$sizeinfo = getimagesize($filepath);
return array('filepath' => 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
* 自学php博客www.zixuephp.cn整理
*/
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 为空
* 自学php博客www.zixuephp.cn整理
*/
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 < $string_length; $i ++) {
$a = ($a + 1) % 256;
$j = ($j + $box [$a]) % 256;
$tmp = $box [$a];
$box [$a] = $box [$j];
$box [$j] = $tmp;
$result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
}
if ($operation == 'DECODE') {
if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 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格式方法
* 自学php博客www.zixuephp.cn整理
*/
function gbkToUtf8($str){
return iconv("GBK", "UTF-8", $str);
}
/**
* 取得输入目录所包含的所有目录和文件
* 以关联数组形式返回
* author: flynetcn
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
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;
}
/**
* 删除文件夹及其文件夹下所有文件
* 自学php博客www.zixuephp.cn整理
*/
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
* @param string $_url
* @return js
* 自学php博客www.zixuephp.cn整理
*/
function alertLocation($_info, $_url) {
echo "
";
exit();
}
/**
* js 弹窗返回
* @param string $_info
* @return js
* 自学php博客www.zixuephp.cn整理
*/
function alertBack($_info) {
echo "
";
exit();
}
/**
* 页面跳转
* @param string $url
* @return js
* 自学php博客www.zixuephp.cn整理
*/
function headerUrl($url) {
echo "
";
exit();
}
/**
* 弹窗关闭
* @param string $_info
* @return js
* 自学php博客www.zixuephp.cn整理
*/
function alertClose($_info) {
echo "
";
exit();
}
/**
* 弹窗
* @param string $_info
* @return js
* 自学php博客www.zixuephp.cn整理
*/
function alert($_info) {
echo "
";
exit();
}
/**
* 系统基本参数上传图片专用
* @param string $_path
* @return null
* 自学php博客www.zixuephp.cn整理
*/
function sysUploadImg($_path) {
echo '
';
echo '
';
echo '
';
echo '
';
}
/**
* html过滤
* @param array|object $_date
* @return string
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
function mysqlString($_data) {
$_data = trim($_data);
return !GPC ? addcslashes($_data) : $_data;
}
/**
* 清理session
* 自学php博客www.zixuephp.cn整理
*/
function unSession() {
if (session_start()) {
session_destroy();
}
}
/**
* 验证是否为空
* @param string $str
* @param string $name
* @return bool (true or false)
* 自学php博客www.zixuephp.cn整理
*/
function validateEmpty($str, $name) {
if (empty($str)) {
self::alertBack('警告:' .$name . '不能为空!');
}
}
/**
* 验证是否相同
* @param string $str1
* @param string $str2
* @param string $alert
* @return JS
* 自学php博客www.zixuephp.cn整理
*/
function validateAll($str1, $str2, $alert) {
if ($str1 != $str2) self::alertBack('警告:' .$alert);
}
/**
* 验证ID
* @param Number $id
* @return JS
* 自学php博客www.zixuephp.cn整理
*/
function validateId($id) {
if (empty($id) || !is_numeric($id)) self::alertBack('警告:参数错误!');
}
/**
* 格式化字符串
* @param string $str
* @return string
* 自学php博客www.zixuephp.cn整理
*/
function formatStr($str) {
$arr = array(' ', ' ', '&', '@', '#', '%', '\'', '"', '\\', '/', '.', ',', '$', '^', '*', '(', ')', '[', ']', '{', '}', '|', '~', '`', '?', '!', ';', ':', '-', '_', '+', '=');
foreach ($arr as $v) {
$str = str_replace($v, '', $str);
}
return $str;
}
/**
* 格式化时间
* @param int $time 时间戳
* @return string
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
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;
}
/**
* 加载 Smarty 模板
* @param string $html
* @return null;
* 自学php博客www.zixuephp.cn整理
*/
function display() {
global $tpl;$html = null;
$htmlArr = explode('/', $_SERVER[SCRIPT_NAME]);
$html = str_ireplace('.php', '.html', $htmlArr[count($htmlArr)-1]);
$dir = dirname($_SERVER[SCRIPT_NAME]);
$firstStr = substr($dir, 0, 1);
$endStr = substr($dir, strlen($dir)-1, 1);
if ($firstStr == '/' || $firstStr == '\\') $dir = substr($dir, 1);
if ($endStr != '/' || $endStr != '\\') $dir = $dir . '/';
$tpl->display($dir.$html);
}
/**
* 创建目录
* @param string $dir
* 自学php博客www.zixuephp.cn整理
*/
function createDir($dir) {
if (!is_dir($dir)) {
mkdir($dir, 0777);
}
}
/**
* 创建文件(默认为空)
* @param unknown_type $filename
* 自学php博客www.zixuephp.cn整理
*/
function createFile($filename) {
if (!is_file($filename)) touch($filename);
}
/**
* 正确获取变量
* @param string $param
* @param string $type
* @return string
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
function delFile($filename) {
if (file_exists($filename)) unlink($filename);
}
/**
* 删除目录
* @param string $path
* 自学php博客www.zixuephp.cn整理
*/
function delDir($path) {
if (is_dir($path)) rmdir($path);
}
/**
* 删除目录及全部子文件
* @param string $dir
* @return bool
* 自学php博客www.zixuephp.cn整理
*/
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;
}
}
}
/**
* 验证登陆
* 自学php博客www.zixuephp.cn整理
*/
function validateLogin() {
if (empty($_SESSION['admin']['user'])) header('Location:/admin/');
}
/**
* 给已经存在的图片添加水印
* @param string $file_path
* @return bool
* 自学php博客www.zixuephp.cn整理
*/
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
* 自学php博客www.zixuephp.cn整理
*/
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 < $startdd + $slen || $slen==0) {
$slen = $str_len - $startdd;
}
$enddd = $startdd + $slen - 1;
for($i=0;$i<$str_len;$i++) {
if($startdd==0) {
$restr .= $c;
} elseif($i > $startdd) {
$restr .= $c;
}
if(ord($str[$i])>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
* 自学php博客www.zixuephp.cn整理
*/
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) < $length + strlen($ar[0][$i]) ) {
$str .= $ar[0][$i];
} else {
break;
}
}
}
return $str;
}
/**
* 删除图片,根据图片ID
* @param int $image_id
* 自学php博客www.zixuephp.cn整理
*/
function delPicByImageId($image_id) {
$db_name = PREFIX . 'images i';
$m = new Model();
$data = $m->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)
* 自学php博客www.zixuephp.cn整理
*/
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($widthratio<$heightratio)
$ratio = $widthratio;
else
$ratio = $heightratio;
}
if($resizewidth_tag && !$resizeheight_tag)
$ratio = $widthratio;
if($resizeheight_tag && !$resizewidth_tag)
$ratio = $heightratio;
$newwidth = $pic_width * $ratio;
$newheight = $pic_height * $ratio;
if(function_exists("imagecopyresampled")) {
$newim = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
} else {
$newim = imagecreate($newwidth,$newheight);
imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
}
$name = $name.$filetype;
imagejpeg($newim,$name);
imagedestroy($newim);
} else {
$name = $name.$filetype;
imagejpeg($im,$name);
}
}
/**
* 下载文件
* @param string $file_path 绝对路径
* 自学php博客www.zixuephp.cn整理
*/
function downFile($file_path) {
//判断文件是否存在
$file_path = iconv('utf-8', 'gb2312', $file_path); //对可能出现的中文名称进行转码
if (!file_exists($file_path)) {
exit('文件不存在!');
}
$file_name = basename($file_path); //获取文件名称
$file_size = filesize($file_path); //获取文件大小
$fp = fopen($file_path, 'r'); //以只读的方式打开文件
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: {$file_size}");
header("Content-Disposition: attachment;filename={$file_name}");
$buffer = 1024;
$file_count = 0;
//判断文件是否结束
while (!feof($fp) && ($file_size-$file_count>0)) {
$file_data = fread($fp, $buffer);
$file_count += $buffer;
echo $file_data;
}
fclose($fp); //关闭文件
}
/**
*创建目录
*/
function mkdirs($dir, $mode = 0777)
{
if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
if (!mkdirs(dirname($dir), $mode)) return FALSE;
return @mkdir($dir, $mode);
}
$val){
$arr2[$val[$key_name]] = $val;
}
return $arr2;
}
/**
* 加密
* @param $str
* @return string
*/
function encrypt($str){
return md5(C("AUTH_CODE").$str);
}
/**
* 获取数组中的某一列
* @param type $arr 数组
* @param type $key_name 列名
* @return type 返回那一列的数组
*/
function get_arr_column($arr, $key_name)
{
$arr2 = array();
foreach($arr as $key => $val){
$arr2[] = $val[$key_name];
}
return $arr2;
}
/**
* 获取url 中的各个参数 类似于 pay_code=alipay&bank_code=ICBC-DEBIT
* @param type $str
* @return type
*/
function parse_url_param($str){
$data = array();
$str = explode('?',$str);
$str = end($str);
$parameter = explode('&',$str);
foreach($parameter as $val){
$tmp = explode('=',$val);
$data[$tmp[0]] = $tmp[1];
}
return $data;
}
/**
* 二维数组排序
* @param $arr
* @param $keys
* @param string $type
* @return array
*/
function array_sort($arr, $keys, $type = 'desc')
{
$key_value = $new_array = array();
foreach ($arr as $k => $v) {
$key_value[$k] = $v[$keys];
}
if ($type == 'asc') {
asort($key_value);
} else {
arsort($key_value);
}
reset($key_value);
foreach ($key_value as $k => $v) {
$new_array[$k] = $arr[$k];
}
return $new_array;
}
/**
* 多维数组转化为一维数组
* @param 多维数组
* @return array 一维数组
*/
function array_multi2single($array)
{
static $result_array = array();
foreach ($array as $value) {
if (is_array($value)) {
array_multi2single($value);
} else
$result_array [] = $value;
}
return $result_array;
}
/**
* 友好时间显示
* @param $time
* @return bool|string
*/
function friend_date($time)
{
if (!$time)
return false;
$fdate = '';
$d = time() - intval($time);
$ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
$md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
$byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
$yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
$dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
$td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
$atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
if ($d == 0) {
$fdate = '刚刚';
} else {
switch ($d) {
case $d < $atd:
$fdate = date('Y年m月d日', $time);
break;
case $d < $td:
$fdate = '后天' . date('H:i', $time);
break;
case $d < 0:
$fdate = '明天' . date('H:i', $time);
break;
case $d < 60:
$fdate = $d . '秒前';
break;
case $d < 3600:
$fdate = floor($d / 60) . '分钟前';
break;
case $d < $dd:
$fdate = floor($d / 3600) . '小时前';
break;
case $d < $yd:
$fdate = '昨天' . date('H:i', $time);
break;
case $d < $byd:
$fdate = '前天' . date('H:i', $time);
break;
case $d < $md:
$fdate = date('m月d日 H:i', $time);
break;
case $d < $ld:
$fdate = date('m月d日', $time);
break;
default:
$fdate = date('Y年m月d日', $time);
break;
}
}
return $fdate;
}
/**
* 返回状态和信息
* @param $status
* @param $info
* @return array
*/
function arrayRes($status, $info, $url = "")
{
return array("status" => $status, "info" => $info, "url" => $url);
}
/**
* @param $arr
* @param $key_name
* @param $key_name2
* @return array
* 将数据库中查出的列表以指定的 id 作为数组的键名 数组指定列为元素 的一个数组
*/
function get_id_val($arr, $key_name,$key_name2)
{
$arr2 = array();
foreach($arr as $key => $val){
$arr2[$val[$key_name]] = $val[$key_name2];
}
return $arr2;
}
// 定义一个函数getIP() 客户端IP,
function getIP(){
if (getenv("HTTP_CLIENT_IP"))
$ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR"))
$ip = getenv("REMOTE_ADDR");
else $ip = "Unknow";
if(preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/', $ip))
return $ip;
else
return '';
}
// 服务器端IP
function serverIP(){
return gethostbyname($_SERVER["SERVER_NAME"]);
}
/**
* 自定义函数递归的复制带有多级子目录的目录
* 递归复制文件夹
* @param type $src 原目录
* @param type $dst 复制到的目录
*/
//参数说明:
//自定义函数递归的复制带有多级子目录的目录
function recurse_copy($src, $dst)
{
$now = time();
$dir = opendir($src);
@mkdir($dst);
while (false !== $file = readdir($dir)) {
if (($file != '.') && ($file != '..')) {
if (is_dir($src . '/' . $file)) {
recurse_copy($src . '/' . $file, $dst . '/' . $file);
}
else {
if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
if (!is_writeable($dst . DIRECTORY_SEPARATOR . $file)) {
exit($dst . DIRECTORY_SEPARATOR . $file . '不可写');
}
@unlink($dst . DIRECTORY_SEPARATOR . $file);
}
if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
@unlink($dst . DIRECTORY_SEPARATOR . $file);
}
$copyrt = copy($src . DIRECTORY_SEPARATOR . $file, $dst . DIRECTORY_SEPARATOR . $file);
if (!$copyrt) {
echo 'copy ' . $dst . DIRECTORY_SEPARATOR . $file . ' failed
';
}
}
}
}
closedir($dir);
}
// 递归删除文件夹
function delFile($dir,$file_type='') {
if(is_dir($dir)){
$files = scandir($dir);
//打开目录 //列出目录中的所有文件并去掉 . 和 ..
foreach($files as $filename){
if($filename!='.' && $filename!='..'){
if(!is_dir($dir.'/'.$filename)){
if(empty($file_type)){
unlink($dir.'/'.$filename);
}else{
if(is_array($file_type)){
//正则匹配指定文件
if(preg_match($file_type[0],$filename)){
unlink($dir.'/'.$filename);
}
}else{
//指定包含某些字符串的文件
if(false!=stristr($filename,$file_type)){
unlink($dir.'/'.$filename);
}
}
}
}else{
delFile($dir.'/'.$filename);
rmdir($dir.'/'.$filename);
}
}
}
}else{
if(file_exists($dir)) unlink($dir);
}
}
/**
* 多个数组的笛卡尔积
*
* @param unknown_type $data
*/
function combineDika() {
$data = func_get_args();
$data = current($data);
$cnt = count($data);
$result = array();
$arr1 = array_shift($data);
foreach($arr1 as $key=>$item)
{
$result[] = array($item);
}
foreach($data as $key=>$item)
{
$result = combineArray($result,$item);
}
return $result;
}
/**
* 两个数组的笛卡尔积
* @param unknown_type $arr1
* @param unknown_type $arr2
*/
function combineArray($arr1,$arr2) {
$result = array();
foreach ($arr1 as $item1)
{
foreach ($arr2 as $item2)
{
$temp = $item1;
$temp[] = $item2;
$result[] = $temp;
}
}
return $result;
}
/**
* 将二维数组以元素的某个值作为键 并归类数组
* array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
* array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
* @param $arr 数组
* @param $key 分组值的key
* @return array
*/
function group_same_key($arr,$key){
$new_arr = array();
foreach($arr as $k=>$v ){
$new_arr[$v[$key]][] = $v;
}
return $new_arr;
}
/**
* 获取随机字符串
* @param int $randLength 长度
* @param int $addtime 是否加入当前时间戳
* @param int $includenumber 是否包含数字
* @return string
*/
function get_rand_str($randLength=6,$addtime=1,$includenumber=0){
if ($includenumber){
$chars='abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
}else {
$chars='abcdefghijklmnopqrstuvwxyz';
}
$len=strlen($chars);
$randStr='';
for ($i=0;$i<$randLength;$i++){
$randStr.=$chars[rand(0,$len-1)];
}
$tokenvalue=$randStr;
if ($addtime){
$tokenvalue=$randStr.time();
}
return $tokenvalue;
}
/**
* CURL请求
* @param $url 请求url地址
* @param $method 请求方法 get post
* @param null $postfields post数据数组
* @param array $headers 请求header信息
* @param bool|false $debug 调试开启 默认false
* @return mixed
*/
function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false) {
$method = strtoupper($method);
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "POST":
curl_setopt($ci, CURLOPT_POST, true);
if (!empty($postfields)) {
$tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
}
break;
default:
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
break;
}
$ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
curl_setopt($ci, CURLOPT_URL, $url);
if($ssl){
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
}
//curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ci, CURLINFO_HEADER_OUT, true);
/*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
$response = curl_exec($ci);
$requestinfo = curl_getinfo($ci);
$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
if ($debug) {
echo "=====post data======\r\n";
var_dump($postfields);
echo "=====info===== \r\n";
print_r($requestinfo);
echo "=====response=====\r\n";
print_r($response);
}
curl_close($ci);
return $response;
//return array($http_code, $response,$requestinfo);
}
/**
* 过滤数组元素前后空格 (支持多维数组)
* @param $array 要过滤的数组
* @return array|string
*/
function trim_array_element($array){
if(!is_array($array))
return trim($array);
return array_map('trim_array_element',$array);
}
/**
* 检查手机号码格式
* @param $mobile 手机号码
*/
function check_mobile($mobile){
if(preg_match('/1[34578]\d{9}$/',$mobile))
return true;
return false;
}
/**
* 检查固定电话
* @param $mobile
* @return bool
*/
function check_telephone($mobile){
if(preg_match('/^([0-9]{3,4}-)?[0-9]{7,8}$/',$mobile))
return true;
return false;
}
/**
* 检查邮箱地址格式
* @param $email 邮箱地址
*/
function check_email($email){
if(filter_var($email,FILTER_VALIDATE_EMAIL))
return true;
return false;
}
/**
* 实现中文字串截取无乱码的方法
*/
function getSubstr($string, $start, $length) {
if(mb_strlen($string,'utf-8')>$length){
$str = mb_substr($string, $start, $length,'utf-8');
return $str.'...';
}else{
return $string;
}
}
/**
* 判断当前访问的用户是 PC端 还是 手机端 返回true 为手机端 false 为PC 端
* @return boolean
*/
/**
* 是否移动端访问访问
*
* @return bool
*/
function isMobile()
{
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
return true;
// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
if (isset ($_SERVER['HTTP_VIA']))
{
// 找不到为flase,否则为true
return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
}
// 脑残法,判断手机发送的客户端标志,兼容性有待提高
if (isset ($_SERVER['HTTP_USER_AGENT']))
{
$clientkeywords = array ('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');
// 从HTTP_USER_AGENT中查找手机浏览器的关键字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
return true;
}
// 协议法,因为有可能不准确,放到最后判断
if (isset ($_SERVER['HTTP_ACCEPT']))
{
// 如果只支持wml并且不支持html那一定是移动设备
// 如果支持wml和html但是wml在html之前则是移动设备
if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
{
return true;
}
}
return false;
}
function is_weixin() {
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
return true;
} return false;
}
function is_qq() {
if (strpos($_SERVER['HTTP_USER_AGENT'], 'QQ') !== false) {
return true;
} return false;
}
function is_alipay() {
if (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
return true;
} return false;
}
//php获取中文字符拼音首字母
function getFirstCharter($str){
if(empty($str))
{
return '';
}
$fchar=ord($str{0});
if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
$s1=iconv('UTF-8','gb2312',$str);
$s2=iconv('gb2312','UTF-8',$s1);
$s=$s2==$str?$s1:$str;
$asc=ord($s{0})*256+ord($s{1})-65536;
if($asc>=-20319&&$asc<=-20284) return 'A';
if($asc>=-20283&&$asc<=-19776) return 'B';
if($asc>=-19775&&$asc<=-19219) return 'C';
if($asc>=-19218&&$asc<=-18711) return 'D';
if($asc>=-18710&&$asc<=-18527) return 'E';
if($asc>=-18526&&$asc<=-18240) return 'F';
if($asc>=-18239&&$asc<=-17923) return 'G';
if($asc>=-17922&&$asc<=-17418) return 'H';
if($asc>=-17417&&$asc<=-16475) return 'J';
if($asc>=-16474&&$asc<=-16213) return 'K';
if($asc>=-16212&&$asc<=-15641) return 'L';
if($asc>=-15640&&$asc<=-15166) return 'M';
if($asc>=-15165&&$asc<=-14923) return 'N';
if($asc>=-14922&&$asc<=-14915) return 'O';
if($asc>=-14914&&$asc<=-14631) return 'P';
if($asc>=-14630&&$asc<=-14150) return 'Q';
if($asc>=-14149&&$asc<=-14091) return 'R';
if($asc>=-14090&&$asc<=-13319) return 'S';
if($asc>=-13318&&$asc<=-12839) return 'T';
if($asc>=-12838&&$asc<=-12557) return 'W';
if($asc>=-12556&&$asc<=-11848) return 'X';
if($asc>=-11847&&$asc<=-11056) return 'Y';
if($asc>=-11055&&$asc<=-10247) return 'Z';
return null;
}
function ajaxReturn($data){
header('Content-Type:application/json; charset=utf-8');
exit(json_encode($data));
}
/**
* 传递数据以易于阅读的样式格式化后输出
* @param [type] $data [description]
* @return [type] [description]
*/
function p($data){
// 定义样式
$str='
';
// 如果是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.='';
echo $str;
}
"0123456789",
2 => "abcdefghijklmnopqrstuvwxyz",
3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
4 => "~@#$%^&*(){}[]|"
);
if ($type == 0) {
array_pop($arr);
$string = implode("", $arr);
} elseif ($type == "-1") {
$string = implode("", $arr);
} else {
$string = $arr[$type];
}
$count = strlen($string) - 1;
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $string[rand(0, $count)];
}
return $code;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/**
* 截取字符串
* [smarty_modifier_truncate description]
* @param [type] $string [description]
* @param integer $length [description]
* @param string $etc [description]
* @param boolean $break_words [description]
* @param boolean $middle [description]
* @return [type] [description]
*/
function truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
if ($length == 0) {
return '';
}
if(strlen($string) > $length){
$length -= min($length,strlen($etc));
$strCut = '';
for($i=0; $i<$length; $i++){
$strCut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i].$string[++$i] : $string[$i];
}
return $strCut.$etc;
}else{
return $string;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 遍历文件夹下所有文件和子文件夹
* @param [type] $path [description]
* @param integer $deep [description]
* @return [type] [description]
*/
function readDirs($dir,$deep=0)
{
$files = [];
if(is_dir($dir)){
if($handle = opendir($dir)){
while (($file = readdir($handle)) !== false) {
if($file != '.' && $file !='..'){
if(is_dir($dir.'/'.file)){
$files[$file] = my_scandir($dir.'/'.$file);
}else{
$files[] = $dir.'/'.$file;
}
}
}
closedir($handle);
return $files;
}
}
}
///////////////////////////////////////////////////////////////////////
/**
* 无限极分类
* @param [type] $list [description]
* @param integer $pid [description]
* @param integer $level [description]
* @return [type] [description]
*/
function get_tree($list, $pid=0, $level=0)
{
static $tree = array();
foreach($list as $row) {
if($row['pid']==$pid) {
$row['level'] = $level;
$tree[] = $row;
get_tree($list, $row['id'], $level + 1);
}
}
return $tree;
}
////////////////////////////////////////////////////////////////////////////////////////////
/**
* 实现具有父子关系的数据分类
* 但不显示自己和自己的子分类
* @param $arr 需要进行分类的数据
* @param $excludeId 父级的ID
* @param int $parent_id 顶级分类的标识默认为0
* @param int $level 层级的缩进
* @return array 返回分类后的数据
*/
function noLimitedCategory($data, $excludeId, $parent_id=0, $level=1)
{
/**
* 对参数$arr进行判断
*/
if(!$data){
return array();
}
if(strtolower(gettype($data))!="array"){
echo "第一个参数希望是一个数据,但是给定的是一个:".gettype($arr);
return;
}
/*定义一个数组变量*/
static $list = array();
foreach($data as $v){
/*如果遍历出来的parent_id与形参parent_id相等*/
if($v['parent_id'] == $parent_id){
/*则添加层级数据*/
$v['level'] = $level;
/*保存到list中*/
$list[] = $v;
/*如果找到被选中的分级那么就跳出循环
递归不执行
不显示子分级*/
if($v['id'] == $excludeId){
continue;
}
/*递归调用$level加1来区分层级*/
$this->noLimitedCategory($data,$excludeId,$v['id'],$level+1);
}
}
/*返回list*/
return $list;
}
//////////////////////////////////////////////////////////////////////////////////////////
/**
* 实现两级分类
* 两级以后的分类全部放到二级,键名为son
* @param array $arr [description]
* @param integer $parent_id [description]
* @param integer $level [description]
* @return [type] [description]
*/
function twoStageCategory($arr=array(), $parent_id=0, $level=1)
{
/**
* 对参数$arr进行判断
*/
if(!$arr){
return array();
}
if(strtolower(gettype($arr))!="array"){
echo "第一个参数希望是一个数据,但是给定的是一个:".gettype($arr);
return;
}
// 用一个静态变量保存修改后的数组
static $list =[];
// 对数组进行遍历
foreach($arr as $k=>$v){ //遍历数组 $arr为二维数组
if($v['parent_id'] == $parent_id){//判断父ID是否相等
$v['level'] = $level; //添加一个键值对
if($v['parent_id'] == 0) { //父ID为0时把$v的值放入临时数组的一维
$list[] = $v;
}else{ //否则在一维$v添加一个下标为son的键值对
$list[count($list)-1]['son'][] = $v;
}
// 这里再调用自己重新遍历
$this->twoStageCategory($arr,$v['id'],$level+1);
}
}
// 返回数组
return $list;
}
/////////////////////////////////////////////////////////////////
/**
* 算出两个文件的相对路径
* @param [string] $path1 [description]
* @param [string] $path2 [description]
* @return [string] [description]
*/
function relative_path($path1, $path2)
{
$arr1 = explode('/', dirname($path1));
$arr2 = explode('/', dirname($path2));
for($i = 0,$len = count($arr2);$i < $len; $i++){
if($arr1[$i] != $arr2[$i]){
break;
}
}
if($i == 1){
$return_path = array();
}
if($i != 1 && $i< $len){
$return_path = array_fill(0, $len-$i, '..');
}
if($i == $len){
$return_path = array('./');
}
$return_path = array_merge($return_path,array_slice($arr1,$i));
return implode('/', $return_path);
}
//////////////////////////////////////////////////////////////////////
/**
* 检查一个字符串是否是合法的日期格式
* @param [type] $data [description]
* @return [type] [description]
*/
function checkDateTime($data)
{
if(date('Y-m-d H:i:s',strtotime($data) == $data)){
return true;
}else{
return false;
}
}
////////////////////////////////////////////////////////////////////////
/**
* 检查是否为一个合法的时间格式
*
* @access public
* @param string $time
* @return void
*/
function is_time($time)
{
$pattern = '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/';
return preg_match($pattern, $time);
}
//////////////////////////////////////////////////////////////
/**
* 验证输入的邮件地址是否合法
*
* @access public
* @param string $email 需要验证的邮件地址
*
* @return bool
*/
function is_email($user_email)
{
$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
{
if (preg_match($chars, $user_email))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
///////////////////////////////////////////////////////////////////////
/**
* 验证是否是邮箱
* @param string $email 邮箱
* @return boolean 是否是邮箱
*/
function is_email($email){
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
return true;
}else{
return false;
}
}
//////////////////////////////////////////////////////////////////////////////////
/**
* 冒泡排序
* @param [type] &$arr [description]
* @return [type] [description]
*/
function bubble_sort(&$arr)
{
for($i = 0, $len = count($arr); $i < $len;$i++){
for($j = 0; $j < $len-1-$i; $j++){
if($arr[$j] > $arr[$j+1]){
$temp = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $temp;
}
}
}
}
//////////////////////////////////////////////////////////////////////
/**
* 遍历文件夹
* @param [string] $dir [目录]
* @param string $childdirLogoStr [标识符]
* @return [type] [description]
*/
function findAllChildFileName($dir,$childdirLogoStr='--')
{
if (is_dir($dir)){
$dirSource = dir($dir);
while ($childFileName = $dirSource->read()){
if(!strcmp($childFileName,".") || !strcmp($childFileName,"..")){
continue;
}
$childFileDir = $dir."/".$childFileName;
if (is_file($childFileDir)){
echo $childdirLogoStr.$childFileName.":文件
";
} else {
echo $childdirLogoStr.$childFileName.":目录
";
findAllChildFileName($childFileDir,"--".$childdirLogoStr);
}
}
$dirSource->close();
}
}
//////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////
/**
* 随机十六进制颜色生成
* @return [type] [description]
*/
function randomColor() {
$str = '#';
for($i = 0 ; $i < 6 ; $i++) {
$randNum = rand(0 , 15);
switch ($randNum) {
case 10: $randNum = 'A'; break;
case 11: $randNum = 'B'; break;
case 12: $randNum = 'C'; break;
case 13: $randNum = 'D'; break;
case 14: $randNum = 'E'; break;
case 15: $randNum = 'F'; break;
}
$str .= $randNum;
}
return $str;
}
/////////////////////////////////////////////////////////////////
/**
* 检查网站是否宕机
* @param [type] $url [description]
*/
function Visit($url)
{
$agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";$ch=curl_init();
curl_setopt ($ch, CURLOPT_URL,$url );
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch,CURLOPT_VERBOSE,false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_SSLVERSION,3);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
$page=curl_exec($ch);
//echo curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300) return true;
else return false;
}
if (Visit("http://www.google.com"))
echo "Website OK"."n";
else
echo "Website DOWN";
///////////////////////////////////////////////////////////
/**
* 随机生成可阅读的字符串
* @param integer $length [description]
* @return [type] [description]
*/
function readable_random_string($length = 6)
{
$conso=array("b","c","d","f","g","h","j","k","l",
"m","n","p","r","s","t","v","w","x","y","z");
$vocal=array("a","e","i","o","u");
$password="";
// srand ((double)microtime()*1000000);
$max = $length/2;
for($i=1; $i<=$max; $i++){
$password.=$conso[rand(0,19)];
$password.=$vocal[rand(0,4)];
}
return $password;
}
////////////////////////////////////////////////////////////////
/**
* 加密解密
* @param [type] $key [description]
* @param [type] $string [description]
* @param [type] $decrypt [description]
* @return [type] [description]
*/
function encryptDecrypt($key, $string, $decrypt){
if($decrypt)
{
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");
return $decrypted;
}else{
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
return $encrypted;
}
}
echo encryptDecrypt(2,'海忠',0);
echo encryptDecrypt(2,'ae0cswcuDMK6iw/J4kGfl8jAdKnUrt9kVE5v33fdaSA=',1);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 获取文件的拓展名
* @param [type] $filename [description]
* @return [type] [description]
*/
function getExtension($filename){
$myext = substr($filename, strrpos($filename, '.'));
return str_replace('.','',$myext);
}
//////////////////////////////////////////////////////////////////////////////////////////
/**
* 格式化文件大小
* @param [type] $size [description]
* @return [type] [description]
*/
function formatSize($size)
{
$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
if ($size == 0) {
return('n/a');
} else {
return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);
}
}
$file = filesize("funcbase-hayden.js");
echo formatSize($file);
////////////////////////////////////////////////////////////////////////////////////////
/**
* 替换标签字符
* @param [type] $string [description]
* @param [type] $replacer [description]
* @return [type] [description]
*/
function stringParser($string,$replacer)
{
$result = str_replace(array_keys($replacer), array_values($replacer),$string);
return $result;
}
//////////////////////////////////////////////////////////////////////////////
/**
* 强制下载文件
* @param [type] $filename [description]
* @return [type] [description]
*/
function download($filename){
if ((isset($filename))&&(file_exists($filename))){
header("Content-length: ".filesize($filename));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile("$filename");
} else {
echo "Looks like file does not exist!";
}
}
/////////////////////////////////////////////////////////////////////////////////////
/**
* 获取用户真实IP
* @return [type] [description]
*/
function getIp() {
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv("HTTP_CLIENT_IP");
else
if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else
if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else
if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "unknown";
return ($ip);
}
///////////////////////////////////////////////////////////////////////////////////////////
/**
*
* 页面提示语跳转
* @param [type] $msgTitle [description]
* @param [type] $message [description]
* @param [type] $jumpUrl [description]
* @return [type] [description]
*/
function message($msgTitle,$message,$jumpUrl){
$str = '';
$str .= '';
$str .= '';
$str .= '
';
$str .= '
页面提示 ';
$str .= '
';
$str .= '';
$str .= '';
$str .= '
'; $str .= '
'.$msgTitle.'
'; $str .= '
'; $str .= '
'.$message.'
'; $str .= '
系统将在 3 秒后自动跳转,如果不想等待,直接点击 这里 跳转
'; $str .= "
"; $str .= '
'; $str .= '
';
$str .= '';
$str .= '';
echo $str;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 计算时长
* @param [type] $seconds [description]
* @return [type] [description]
*/
function changeTimeType($seconds) {
if ($seconds > 3600) {
$hours = intval($seconds / 3600);
$minutes = $seconds % 3600;
$time = $hours . ":" . gmstrftime('%M:%S', $minutes);
} else {
$time = gmstrftime('%H:%M:%S', $seconds);
}
return $time;
}
/////////////////////////////////////////////////////////////////
/**
* 获取当前月份第一天和最后一天
* @param [type] $date [description]
* @return [type] [description]
*/
function getthemonth($date){
$firstday = date('Y-m-01', strtotime($date));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
return array($firstday,$lastday);
}
$today = date("Y-m-d");
$day=getthemonth($today);
echo "当月的第一天: ".$day[0]." 当月的最后一天: ".$day[1];
//////////////////////////////////////////////////////////////////////////////
/**
* 短网址
* @param [type] $x [description]
* @return [type] [description]
*/
function code62($x){
$show='';
while($x>0){
$s=$x % 62;
if ($s>35){
$s=chr($s+61);
}elseif($s>9&&$s<=35){
$s=chr($s+55);
}
$show.=$s;
$x=floor($x/62);
}
return $show;
}
function shorturl($url){
$url=crc32($url);
$result=sprintf("%u",$url);
return code62($result);
}
echo shorturl('http://www.helloweba.com/');
/////////////////////////////////////////////////////////////////////////////
/**
* 时间轴
* @param [type] $time [description]
* @return [type] [description]
*/
function tranTime($time) {
$rtime = date("m-d H:i",$time);
$htime = date("H:i",$time);
$time = time() - $time;
if ($time < 60) {
$str = '刚刚';
}
elseif ($time < 60 * 60) {
$min = floor($time/60);
$str = $min.'分钟前';
}
elseif ($time < 60 * 60 * 24) {
$h = floor($time/(60*60));
$str = $h.'小时前 '.$htime;
}
elseif ($time < 60 * 60 * 24 * 3) {
$d = floor($time/(60*60*24));
if($d==1)
$str = '昨天 '.$rtime;
else
$str = '前天 '.$rtime;
}
else {
$str = $rtime;
}
return $str;
}
echo tranTime(strtotime("2016-7-15 15:40"));
//////////////////////////////////////////////////////////////////////////////////////////
/**
* 格式化输出用户发布时间
* @param [type] $say [description]
* @param [type] $dt [description]
* @param [type] $uid [description]
* @return [type] [description]
*/
function formatSay($say,$dt,$uid){
$say=htmlspecialchars(stripslashes($say));
return'
demo_'.$uid.' '. preg_replace('/((?:http|https|ftp):\/\/(?:[A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+): ?(\d+)?\/?[^\s\"\']+)/i','http://www.voidcn.com/tag/$1',$say).'
'.tranTime($dt).'
';
}
/////////////////////////////////////////////////////////////////////////////////////////////
/**
* 数组转换为XML
* @param [type] $arr [description]
* @return [type] [description]
*/
function arrayToXml($arr)
{
$xml = "
"; foreach ($arr as $key=>$val) { if (is_numeric($val)){ $xml.="<".$key.">".$val."
"; }else{ $xml.="<".$key.">".$val."
"; } } $xml.="
";
return $xml;
}
/**
* XML转换为数组
* @param [type] $xml [description]
* @return [type] [description]
*/
function xmlToArray($xml)
{
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}
///////////////////////////////////////////////////////////////////////////////////
/**
* curl数据传输
* @param [type] $url [description]
* @param [type] $data [description]
* @return [type] [description]
*/
function ppd_curl($url,$data = null)
{
//\Think\Log::record($url,'INFO');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
///////////////////////////////////////////////////////////////////////
/**
*数字金额转换成中文大写金额的函数
*String Int $num 要转换的小写数字或小写字符串
*return 大写字母
*小数位为两位
**/
function get_amount($num){
$c1 = "零壹贰叁肆伍陆柒捌玖";
$c2 = "分角元拾佰仟万拾佰仟亿";
$num = round($num, 2);
$num = $num * 100;
if (strlen($num) > 10) {
return "数据太长,没有这么大的钱吧,检查下";
}
$i = 0;
$c = "";
while (1) {
if ($i == 0) {
$n = substr($num, strlen($num)-1, 1);
} else {
$n = $num % 10;
}
$p1 = substr($c1, 3 * $n, 3);
$p2 = substr($c2, 3 * $i, 3);
if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
$c = $p1 . $p2 . $c;
} else {
$c = $p1 . $c;
}
$i = $i + 1;
$num = $num / 10;
$num = (int)$num;
if ($num == 0) {
break;
}
}
$j = 0;
$slen = strlen($c);
while ($j < $slen) {
$m = substr($c, $j, 6);
if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
$left = substr($c, 0, $j);
$right = substr($c, $j + 3);
$c = $left . $right;
$j = $j-3;
$slen = $slen-3;
}
$j = $j + 3;
}
if (substr($c, strlen($c)-3, 3) == '零') {
$c = substr($c, 0, strlen($c)-3);
}
if (empty($c)) {
return "零元整";
}else{
return $c . "整";
}
}
//echo get_amount(208.2);die();
///////////////////////////////////////////////////////////////////////////////////////
/**
* 删除指定的标签和内容
* @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[]='/(<'.$tag.'.*?>[\s|\S]*?<\/'.$tag.'>)/';
}
$data=preg_replace($html,'',$str);
}else{
$html=array();
foreach ($tags as $tag) {
$html[]="/(<(?:\/".$tag."|".$tag.")[^>]*>)/i";
}
$data=preg_replace($html, '', $str);
}
return $data;
}
//echo strip_html_tags(array('a'),$str,1);
///////////////////////////////////////////////////////////////////////////
/**
* 文件夹复制函数
* @param [type] $src [description]
* @param [type] $dst [description]
* @return [type] [description]
*/
function recurse_copy($src,$dst) { // 原目录,复制到的目录
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
echo recurse_copy("原文件夹","目录文件夹");
/////////////////////////////////////////////////////////////////////////////
/**
* 系统加密方法
* @param string $data 要加密的字符串
* @param string $key 加密密钥
* @param int $expire 过期时间 单位 秒
* @return string
* @author 麦当苗儿
*/ function think_encrypt($data, $key = '', $expire = 0) { $key = md5(empty($key) ? C('DATA_AUTH_KEY') : $key); $data = base64_encode($data); $x = 0; $len = strlen($data); $l = strlen($key); $char = ''; for ($i = 0; $i < $len; $i++) { if ($x == $l) $x = 0; $char .= substr($key, $x, 1); $x++; } $str = sprintf('%010d', $expire ? $expire + time():0); for ($i = 0; $i < $len; $i++) { $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256); } return str_replace(array('+','/','='),array('-','_',''),base64_encode($str)); } //////////////////////////////////////////////////////////////////////////////// /** * 系统解密方法 * @param string $data 要解密的字符串 (必须是think_encrypt方法加密的字符串) * @param string $key 加密密钥 * @return string * @author 麦当苗儿
*/ function think_decrypt($data, $key = ''){ $key = md5(empty($key) ? C('DATA_AUTH_KEY') : $key); $data = str_replace(array('-','_'),array('+','/'),$data); $mod4 = strlen($data) % 4; if ($mod4) { $data .= substr('====', $mod4); } $data = base64_decode($data); $expire = substr($data,0,10); $data = substr($data,10); if($expire > 0 && $expire < time()) { return ''; } $x = 0; $len = strlen($data); $l = strlen($key); $char = $str = ''; for ($i = 0; $i < $len; $i++) { if ($x == $l) $x = 0; $char .= substr($key, $x, 1); $x++; } for ($i = 0; $i < $len; $i++) { if (ord(substr($data, $i, 1))
$v) { $fieldArr[$k] = $v[$field]; } $sort = $desc == false ? SORT_ASC : SORT_DESC; array_multisort($fieldArr, $sort, $array); }
