Home > php教程 > php手册 > 110 custom php functions

110 custom php functions

PHP中文网
Release: 2016-10-17 09:12:04
Original
1008 people have browsed it

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;
}
Copy after login

/**
* 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(&#39;SENSITIVE&#39;);
    import("ORG.SensitiveFilter");
    $arr=SensitiveFilter::getWord();
    foreach ($arr as $v) {
        if (false !== strstr($content, $v)){
            $content=str_replace($v,&#39;***&#39;,$content);//内容中存在敏感词库中的敏感词,则将敏感词用*替换
        }
    }
    return $content;
 }
Copy after login

/**
*The passed data is formatted in an easy-to-read style and output
*/

function p($data){
    // 定义样式
    $str=&#39;<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;">&#39;;
    // 如果是boolean或者null直接显示文字;否则print
    if (is_bool($data)) {
        $show_data=$data ? &#39;true&#39; : &#39;false&#39;;
    }elseif (is_null($data)) {
        $show_data=&#39;null&#39;;
    }else{
        $show_data=print_r($data,true);
    }
    $str.=$show_data;
    $str.=&#39;
'; echo $str; }
Copy after login

/**
* 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(&#39;max_execution_time&#39;, &#39;0&#39;);
    // 去除两边的/
    $path=trim($path,&#39;.&#39;);
    $path=trim($path,&#39;/&#39;);
    $config=array(
        &#39;rootPath&#39;  =>&#39;./&#39;,         //文件上传保存的根路径
        &#39;savePath&#39;  =>&#39;./&#39;.$path.&#39;/&#39;,   
        &#39;exts&#39;      => array(&#39;jpg&#39;, &#39;gif&#39;, &#39;png&#39;, &#39;jpeg&#39;,&#39;bmp&#39;),
        &#39;maxSize&#39;   => $maxSize,
        &#39;autoSub&#39;   => true,
        );
    $upload = new \Think\Upload($config);// 实例化上传类
    $info = $upload->upload();
    if($info) {
        foreach ($info as $k => $v) {
            $data[]=trim($v[&#39;savepath&#39;],&#39;.&#39;).$v[&#39;savename&#39;];
        }
        return $data;
    }
}
Copy after login

/**
* Alibaba Cloud OSS operation
* Instantiate Alibaba Cloud oos
* @return object The object obtained by instantiation
*/

function new_oss(){
    vendor(&#39;Alioss.autoload&#39;);
    $config=C(&#39;ALIOSS_CONFIG&#39;);
    $oss=new \OSS\OssClient($config[&#39;KEY_ID&#39;],$config[&#39;KEY_SECRET&#39;],$config[&#39;END_POINT&#39;]);
    return $oss;
}
Copy after login

/ **
* 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=&#39;M_Upload/zhuanti/content/&#39;.$id;
    $accessKeyId=C(&#39;ALIOSS_CONFIG.KEY_ID&#39;);
    $accessKeySecret=C(&#39;ALIOSS_CONFIG.KEY_SECRET&#39;);
    $endpoint=C(&#39;ALIOSS_CONFIG.END_POINT&#39;);
    $bucket=C(&#39;ALIOSS_CONFIG.BUCKET&#39;);
    //$oss->putObject($bucket,$id,$str);
    vendor(&#39;Alioss.autoload&#39;);
    $config=C(&#39;ALIOSS_CONFIG&#39;);
    $ossClient=new \OSS\OssClient($config[&#39;KEY_ID&#39;],$config[&#39;KEY_SECRET&#39;],$config[&#39;END_POINT&#39;]);
    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;
}
Copy after login

/**
* 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(&#39;ALIOSS_CONFIG.KEY_ID&#39;);
    $accessKeySecret=C(&#39;ALIOSS_CONFIG.KEY_SECRET&#39;);
    $endpoint=C(&#39;ALIOSS_CONFIG.END_POINT&#39;);
    $bucket=C(&#39;ALIOSS_CONFIG.BUCKET&#39;);
    //$oss->putObject($bucket,$id,$str);
    try {
        vendor(&#39;Alioss.autoload&#39;);
        $config=C(&#39;ALIOSS_CONFIG&#39;);
        $ossClient=new \OSS\OssClient($config[&#39;KEY_ID&#39;],$config[&#39;KEY_SECRET&#39;],$config[&#39;END_POINT&#39;]);
        $content=$ossClient->getObject($bucket, $id);
        print("object content: " . $content);
    } catch (OssException $e) {
        print $e->getMessage();
    }
}
Copy after login

/**
* 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(&#39;ALIOSS_CONFIG.BUCKET&#39;);
    // 先统一去除左侧的.或者/ 再添加./
    $oss_path=ltrim($path,&#39;./&#39;);
    $path=&#39;./&#39;.$oss_path;
    if (file_exists($path)) {
        // 实例化oss类
        $oss=new_oss();
        // 上传到oss    
        $oss->uploadFile($bucket,$oss_path,$path);
        // 如需上传到oss后 自动删除本地的文件 则删除下面的注释 
        unlink($path);
        return true;
    }
    return false;
}
Copy after login

/**
* 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(&#39;ALIOSS_CONFIG.BUCKET&#39;);
    $test=$oss->deleteObject($bucket,$object);
}
Copy after login

/**
* 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 &#39;&#39;;
    }
    // 如果已经有http直接返回
    if (strpos($path, &#39;http://&#39;)!==false) {
        return $path;
    }
    // 判断是否使用了oss
    $alioss=C(&#39;ALIOSS_CONFIG&#39;);
    if (empty($alioss[&#39;KEY_ID&#39;])) {
        return &#39;http://&#39;.$_SERVER[&#39;HTTP_HOST&#39;].$path;
    }else{
        $path=ltrim($path,&#39;.&#39;);
        return &#39;http://&#39;.$alioss[&#39;BUCKET&#39;].&#39;.&#39;.$alioss[&#39;END_POINT&#39;].$path;
    }
    
}
Copy after login

/**
* app video upload
* @return string uploaded video name
*/

function app_upload_video($path,$maxSize=52428800){
    ini_set(&#39;max_execution_time&#39;, &#39;0&#39;);
    // 去除两边的/
    $path=trim($path,&#39;.&#39;);
    $path=trim($path,&#39;/&#39;);
    $config=array(
        &#39;rootPath&#39;  =>&#39;./&#39;,         //文件上传保存的根路径
        &#39;savePath&#39;  =>&#39;./&#39;.$path.&#39;/&#39;,   
        &#39;exts&#39;      => array(&#39;mp4&#39;,&#39;avi&#39;,&#39;3gp&#39;,&#39;rmvb&#39;,&#39;gif&#39;,&#39;wmv&#39;,&#39;mkv&#39;,&#39;mpg&#39;,&#39;vob&#39;,&#39;mov&#39;,&#39;flv&#39;,&#39;swf&#39;,&#39;mp3&#39;,&#39;ape&#39;,&#39;wma&#39;,&#39;aac&#39;,&#39;mmf&#39;,&#39;amr&#39;,&#39;m4a&#39;,&#39;m4r&#39;,&#39;ogg&#39;,&#39;wav&#39;,&#39;wavpack&#39;),
        &#39;maxSize&#39;   => $maxSize,
        &#39;autoSub&#39;   => true,
        );
    $upload = new \Think\Upload($config);// 实例化上传类
    $info = $upload->upload();
    if($info) {
        foreach ($info as $k => $v) {
            $data[]=trim($v[&#39;savepath&#39;],&#39;.&#39;).$v[&#39;savename&#39;];
        }
        return $data;
    }
}
Copy after login

/**
* Return file format
* @param string $str file name
* @return string file format
*/

function file_format($str){
    // 取文件后缀名
    $str=strtolower(pathinfo($str, PATHINFO_EXTENSION));
    // 图片格式
    $image=array(&#39;webp&#39;,&#39;jpg&#39;,&#39;png&#39;,&#39;ico&#39;,&#39;bmp&#39;,&#39;gif&#39;,&#39;tif&#39;,&#39;pcx&#39;,&#39;tga&#39;,&#39;bmp&#39;,&#39;pxc&#39;,&#39;tiff&#39;,&#39;jpeg&#39;,&#39;exif&#39;,&#39;fpx&#39;,&#39;svg&#39;,&#39;psd&#39;,&#39;cdr&#39;,&#39;pcd&#39;,&#39;dxf&#39;,&#39;ufo&#39;,&#39;eps&#39;,&#39;ai&#39;,&#39;hdri&#39;);
    // 视频格式
    $video=array(&#39;mp4&#39;,&#39;avi&#39;,&#39;3gp&#39;,&#39;rmvb&#39;,&#39;gif&#39;,&#39;wmv&#39;,&#39;mkv&#39;,&#39;mpg&#39;,&#39;vob&#39;,&#39;mov&#39;,&#39;flv&#39;,&#39;swf&#39;,&#39;mp3&#39;,&#39;ape&#39;,&#39;wma&#39;,&#39;aac&#39;,&#39;mmf&#39;,&#39;amr&#39;,&#39;m4a&#39;,&#39;m4r&#39;,&#39;ogg&#39;,&#39;wav&#39;,&#39;wavpack&#39;);
    // 压缩格式
    $zip=array(&#39;rar&#39;,&#39;zip&#39;,&#39;tar&#39;,&#39;cab&#39;,&#39;uue&#39;,&#39;jar&#39;,&#39;iso&#39;,&#39;z&#39;,&#39;7-zip&#39;,&#39;ace&#39;,&#39;lzh&#39;,&#39;arj&#39;,&#39;gzip&#39;,&#39;bz2&#39;,&#39;tz&#39;);
    // 文档格式
    $text=array(&#39;exe&#39;,&#39;doc&#39;,&#39;ppt&#39;,&#39;xls&#39;,&#39;wps&#39;,&#39;txt&#39;,&#39;lrc&#39;,&#39;wfs&#39;,&#39;torrent&#39;,&#39;html&#39;,&#39;htm&#39;,&#39;java&#39;,&#39;js&#39;,&#39;css&#39;,&#39;less&#39;,&#39;php&#39;,&#39;pdf&#39;,&#39;pps&#39;,&#39;host&#39;,&#39;box&#39;,&#39;docx&#39;,&#39;word&#39;,&#39;perfect&#39;,&#39;dot&#39;,&#39;dsf&#39;,&#39;efe&#39;,&#39;ini&#39;,&#39;json&#39;,&#39;lnk&#39;,&#39;log&#39;,&#39;msi&#39;,&#39;ost&#39;,&#39;pcs&#39;,&#39;tmp&#39;,&#39;xlsb&#39;);
    // 匹配不同的结果
    switch ($str) {
        case in_array($str, $image):
            return &#39;image&#39;;
            break;
        case in_array($str, $video):
            return &#39;video&#39;;
            break;
        case in_array($str, $zip):
            return &#39;zip&#39;;
            break;
        case in_array($str, $text):
            return &#39;text&#39;;
            break;
        default:
            return &#39;image&#39;;
            break;
    }
}
Copy after login

/**
* 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(&#39;OauthUser&#39;)->getToken($uid,2);
    // 如果没有token说明移动端没有登录;则不发送通知
    if (empty($device_tokens)) {
        return false;
    }
    // 导入友盟
    Vendor(&#39;Umeng.Umeng&#39;);
    // 自定义字段   根据实际环境分配;如果不用可以忽略
    $status=1;
    // 消息未读总数统计  根据实际环境获取未读的消息总数 此数量会显示在app图标右上角
    $count_number=1;
    $data=array(
        &#39;key&#39;=>&#39;status&#39;,
        &#39;value&#39;=>"$status",
        &#39;count_number&#39;=>$count_number
        );
    // 判断device_token  64位表示为苹果 否则为安卓
    if(strlen($device_tokens)==64){
        $key=C(&#39;UMENG_IOS_APP_KEY&#39;);
        $timestamp=C(&#39;UMENG_IOS_SECRET&#39;);
        $umeng=new \Umeng($key, $timestamp);
        $umeng->sendIOSUnicast($data,$title,$device_tokens);
    }else{
        $key=C(&#39;UMENG_ANDROID_APP_KEY&#39;);
        $timestamp=C(&#39;UMENG_ANDROID_SECRET&#39;);
        $umeng=new \Umeng($key, $timestamp);
        $umeng->sendAndroidUnicast($data,$title,$device_tokens);
    }
    return true;
}
Copy after login

/**
* Return user id
* @return integer user id
*/

function get_uid(){
    return $_SESSION[&#39;user&#39;][&#39;id&#39;];//根据自己登录的时候保存的SESSION元素而定
}
Copy after login

/* *
* 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=&#39;&#39;,$error_message=&#39;成功&#39;,$error_code=1){
    $all_data=array(
        &#39;error_code&#39;=>$error_code,
        &#39;error_message&#39;=>$error_message,
        );
    if ($data!==&#39;&#39;) {
        $all_data[&#39;data&#39;]=$data;
        // app 禁止使用和为了统一字段做的判断
        $reserved_words=array(&#39;id&#39;,&#39;title&#39;,&#39;price&#39;,&#39;product_title&#39;,&#39;product_id&#39;,&#39;product_category&#39;,&#39;product_number&#39;);
        foreach ($reserved_words as $k => $v) {
            if (array_key_exists($v, $data)) {
                echo &#39;app不允许使用【&#39;.$v.&#39;】这个键名 —— 此提示是function.php 中的ajax_return函数返回的&#39;;
                die;
            }
        }
    }
    // 如果是ajax或者app访问;则返回json数据 pc访问直接p出来
    echo json_encode($all_data);
    exit(0);
}
Copy after login

/**
* Check whether you are logged in
* @return boolean Whether you are logged in
*/

function check_login(){
    if (!empty($_SESSION[&#39;user&#39;][&#39;id&#39;])){
        return true;
    }else{
        return false;
    }
}
Copy after login

/**
* Obtain the corresponding key and secret according to the configuration item
* @return array key and secret
*/

function get_rong_key_secret(){
    // 判断是需要开发环境还是生产环境的key
    if (C(&#39;RONG_IS_DEV&#39;)) {
        $key=C(&#39;RONG_DEV_APP_KEY&#39;);
        $secret=C(&#39;RONG_DEV_APP_SECRET&#39;);
    }else{
        $key=C(&#39;RONG_PRO_APP_KEY&#39;);
        $secret=C(&#39;RONG_PRO_APP_SECRET&#39;);
    }
    $data=array(
        &#39;key&#39;=>$key,
        &#39;secret&#39;=>$secret
        );
    return $data;
}
Copy after login

/**
* Get Rongyun token
* @param integer $uid user id
* @return integer token
*/

function get_rongcloud_token($uid){
    // 从数据库中获取token
    $token=D(&#39;OauthUser&#39;)->getToken($uid,1);
    // 如果有token就返回
    if ($token) {
        return $token;
    }
    // 获取用户昵称和头像
    $user_data=M(&#39;Users&#39;)->field(&#39;username,avatar&#39;)->getById($uid);
    // 用户不存在
    if (empty($user_data)) {
        return false;
    }
    // 获取头像url格式
    $avatar=get_url($user_data[&#39;avatar&#39;]);
    // 获取key和secret
    $key_secret=get_rong_key_secret();
    // 实例化融云
    $rong_cloud=new \Org\Xb\RongCloud($key_secret[&#39;key&#39;],$key_secret[&#39;secret&#39;]);
    // 获取token
    $token_json=$rong_cloud->getToken($uid,$user_data[&#39;username&#39;],$avatar);
    $token_array=json_decode($token_json,true);
    // 获取token失败
    if ($token_array[&#39;code&#39;]!=200) {
        return false;
    }
    $token=$token_array[&#39;token&#39;];
    $data=array(
        &#39;uid&#39;=>$uid,
        &#39;type&#39;=>1,
        &#39;nickname&#39;=>$user_data[&#39;username&#39;],
        &#39;head_img&#39;=>$avatar,
        &#39;access_token&#39;=>$token
        );
    // 插入数据库
    $result=D(&#39;OauthUser&#39;)->addData($data);
    if ($result) {
        return $token;
    }else{
        return false;
    }
}
Copy after login

/**
* Update Rongyun avatar
* @param integer $uid user id
* @return boolean Whether the operation was successful
*/

function refresh_rongcloud_token($uid){
    // 获取用户昵称和头像
    $user_data=M(&#39;Users&#39;)->field(&#39;username,avatar&#39;)->getById($uid);
    // 用户不存在
    if (empty($user_data)) {
        return false;
    }
    $avatar=get_url($user_data[&#39;avatar&#39;]);
    // 获取key和secret
    $key_secret=get_rong_key_secret();
    // 实例化融云
    $rong_cloud=new \Org\Xb\RongCloud($key_secret[&#39;key&#39;],$key_secret[&#39;secret&#39;]);
    // 更新融云用户头像
    $result_json=$rong_cloud->userRefresh($uid,$user_data[&#39;username&#39;],$avatar);
    $result_array=json_decode($result_json,true);
    if ($result_array[&#39;code&#39;]==200) {
        return true;
    }else{
        return false;
    }
}
Copy after login



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template