Compiled 110 commonly used custom PHP functions, including image operations, Alibaba Cloud OSS, file downloads, SMS verification codes, etc.
header("Content-type: text/html;charset=utf-8" );
/* * 定义发送短信验证码方法 * 使用php自带的SoapClient类来获取短信接口数据 * 该接口的自动发送验证码方法是Submit()方法 */ function phonecode($phone){ $soap=new SoapClient('http://101.201.52.251:7801/sms?wsdl'); $code=''; for($i=0;$i<6;$i++){ $code.=rand(0,9);//生成6位随机字符的验证码 } $str="【XXXX】网站注册验证码:".$code.",十五分钟内输入有效。如非本人操作,请忽略此消息。"; $res=$soap->Submit("210007","XXXXX","XXXX",$str,$phone); return $code; }
/**
* Determine whether there are sensitive words in user input
* You need to add the sensitive word class file SensitiveFilter.php in the ORG extension folder of ThinkPHP
*/
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; }
/**
*The passed data is formatted in an easy-to-read style and output
*/
function p($data){ // 定义样式 $str='<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 13px;line-height: 1.42857;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">'; // 如果是boolean或者null直接显示文字;否则print if (is_bool($data)) { $show_data=$data ? 'true' : 'false'; }elseif (is_null($data)) { $show_data='null'; }else{ $show_data=print_r($data,true); } $str.=$show_data; $str.=''; echo $str; }
/**
* app image upload
* $path the path of the uploaded image
* $maxSize the size control of the uploaded image
* @return string the name of the uploaded image
*/
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; } }
/**
* Alibaba Cloud OSS operation
* Instantiate Alibaba Cloud oos
* @return object The object obtained by instantiation
*/
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; }
/ **
* Alibaba Cloud OSS operation
* Upload object
* key Use the id of the topic to identify the topic of this film
* $str is the content of the topic to be uploaded
*/
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; }
/**
* Alibaba Cloud OSS operation
* Upload object
* key Use the id of the topic to identify the topic of this film
* $str is the content of the topic to be uploaded
*/
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(); } }
/**
* Alibaba Cloud OSS operation
* Upload files to Alibaba Cloud OSS and delete local files
* @param string $path File path
* @return bollear Whether to upload
*/
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; }
/**
* Alibaba Cloud OSS operation
* Delete the specified file on Alibaba Cloud OSS
* @param string $object file path For example, delete the /Public/README.md file and pass Public/README.md
*/
function oss_delet_object($object){ // 实例化oss类 $oss=new_oss(); // 获取bucket名称 $bucket=C('ALIOSS_CONFIG.BUCKET'); $test=$oss->deleteObject($bucket,$object); }
/**
* Alibaba Cloud OSS operation
* Get complete network connection
* @param string $path file path
* @return string http connection
* /
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 video upload
* @return string uploaded video name
*/
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; } }
/**
* Return file format
* @param string $str file name
* @return string file format
*/
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; } }
/**
* Send Umeng push message
* @param integer $uid user id
* @param string $title The title of the push
* @return boolean Whether it was successful
*/
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; }
/**
* Return user id
* @return integer user id
*/
function get_uid(){ return $_SESSION['user']['id'];//根据自己登录的时候保存的SESSION元素而定 }
/* *
* Return json format data of iso, Android, ajax
* @param array $data Data that needs to be sent to the front end
* @param string $error_message Success or error prompt
* @param integer $error_code Status code: 0: Success 1: Failure
* @return string data in json format
*/
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); }
/**
* Check whether you are logged in
* @return boolean Whether you are logged in
*/
function check_login(){ if (!empty($_SESSION['user']['id'])){ return true; }else{ return false; } }
/**
* Obtain the corresponding key and secret according to the configuration item
* @return array key and secret
*/
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; }
/**
* Get Rongyun token
* @param integer $uid user id
* @return integer token
*/
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; } }
/**
* Update Rongyun avatar
* @param integer $uid user id
* @return boolean Whether the operation was successful
*/
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; } }