开发中遇到的一些有用的东西

  /**
     * 批量导入数据
     * @router get importData auth:public
     */
    function importData(){

         $filename = "sales.csv";
         $excelData = array();
         $content = trim(file_get_contents($filename));
         $excelData = explode("
", $content);
         //将这个10W+ 的数组分割成5000一个的小数组。这样就一次批量插入5000条数据。mysql 是支持的
         $chunkData = array_chunk($excelData, 5000);
         $count = count($chunkData);
         for($i = 0; $i< $count; $i++){
             $insertRows = array();
             foreach($chunkData[$i] as $value){
                 $string = mb_convert_encoding(trim(strip_tags($value)), 'utf-8', 'gbk');
                 $v = explode(',', trim($string));
                 $row = array();
                 $row['bankCode'] = $v[0];
                 $row['drctCode'] = $v[2];
                 $row['name'] = $v[3];
                 $insertRows[] = $row;
             }
             $result = PubBankCode::open()->addMass($insertRows);
        }

    }

  


//获取某个文件夹下文件的个数 $dir = '/data/downloadFile/showqrcode'; $handler = opendir($dir); $fileCount = count(scandir($dir)) - 2; if($fileCount <=3){ }

  


//读取文件夹中文件的名称 $imageName = []; $handler = opendir('/data/downloadFile/showqrcode'); //2、循环的读取目录下的所有文件 //其中$filename = readdir($handler)是每次循环的时候将读取的文件名赋值给$filename,为了不陷于死循环,所以还要让$filename !== false。一定要用!==,因为如果某个文件名如果叫’0′,或者某些被系统认为是代表false,用!=就会停止循环*/ while( ($filename = readdir($handler)) !== false ) { //3、目录下都会有两个文件,名字为’.'和‘..’,不要对他们进行操作 if($filename != "." && $filename != ".."){ //4、进行处理 //这里简单的用echo来输出文件名 array_push($imageName, $filename); } } poolMemcached::set('imageName', json_encode($imageName)); $imageName = json_decode(poolMemcached::get('imageName')); closedir($handler); return $imageName;

  


//微信服务器向配置服务器发送的信息 public function urlRedirect() { $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; $wechatDemo = new WechatApi(); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); // $orgin_id = $_GET["orgid"]; $fromUsername = (string)$postObj->FromUserName; $Event = trim((string)$postObj->Event); $EventKey = trim((string)$postObj->EventKey); $crateTime = trim((string)$postObj->CreateTime); $flag = $fromUsername.$crateTime; //处理微信重复发送三次响应 if($Event == "subscribe"){ //判断是未关注 if(isset($EventKey) && isset($postObj->Ticket)){ //判断是扫码 $code = explode('_', $EventKey)[1]; $get_flag = poolMemcached::get($fromUsername); //通过openId和createTime是可以判断微信的响应是否重复 if(isset($get_flag) && !empty($get_flag)){ if($get_flag == $flag){ echo "success"; poolMemcached::delete($fromUsername); exit(); } }else{ poolMemcached::set($fromUsername, $flag, 60); } } } }else{ if($Event == "SCAN"){ $get_flag = poolMemcached::get($fromUsername); if(isset($get_flag) && !empty($get_flag)){ if($get_flag == $flag){ echo "success"; poolMemcached::delete($fromUsername); exit(); } }else{ poolMemcached::set($fromUsername, $flag, 60); } }else{ if($Event == "CLICK"){ $key = trim((string)$postObj->EventKey); if($key == "V1001_GOOD"){ $msg = "谢谢点赞"; // $this->sendMessage($fromUsername, $msg); $media_id = "29SlbVhQ7a96HDr4ExW_ROC2vz4s3p7TVXc1Pe5QmYU"; $wechatDemo->sendTextMessage($fromUsername, $msg); } }else{ if($Event == "unsubscribe"){ $msg = "取消关注"; $this->sendMessage($fromUsername, $msg); }else{ echo ""; } } } } // if (count($keyArray) == 1){ //已关注者扫描 // $this->sendMessage($fromUsername, $Event); // }else{ // //未关注者关注后推送事件 // $this->sendMessage($fromUsername, $Event); // } }

  


/** * 功能:php完美实现下载远程图片保存到本地 * 参数:文件url,保存文件目录,保存文件名称,使用的下载方式 * 当保存文件名称为空时则使用远程文件原来的名称 * @param $url * @param string $filename * @param int $type * @return array */ function saveRemoteImg($url, $filename='',$type=0){ if(trim($url)==''){ return array('file_name'=>'','save_path'=>'','error'=>1); } if(trim($filename)==''){//保存文件名 $ext=strrchr($url,'.'); if($ext!='.gif'&&$ext!='.jpg'){ return array('file_name'=>'','save_path'=>'','error'=>3); } }
//文件保存目录
$save_dir = "/data/downloadFile/showqrcode/"; //创建保存目录 //if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){ // return array('file_name'=>'','save_path'=>'','error'=>5); //} //获取远程文件所采用的方法 if($type){ $ch=curl_init(); $timeout=5; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $img=curl_exec($ch); curl_close($ch); }else{ ob_start(); readfile($url); $img=ob_get_contents(); ob_end_clean(); } //$size=strlen($img); //文件大小 $fp2=@fopen($save_dir.$filename,'a'); fwrite($fp2,$img); fclose($fp2); unset($img,$url); return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0); }

public function valid($data) { $echoStr = $data["echostr"]; //valid signature , option if($this->checkSignature($data)){ echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = file_get_contents('php://input'); //extract post data if(!empty($postStr)){ /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; if(!empty($keyword)){ $msgType = "text"; $contentStr = "Welcome to wechat world!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else{ echo "Input something..."; } }else{ echo ""; exit; } } private function checkSignature($data) { // you must define TOKEN by yourself if(!defined("TOKEN")){ throw new Exception('TOKEN is not defined!'); } $signature = $data["signature"]; $timestamp = $data["timestamp"]; $nonce = $data["nonce"]; $token = TOKEN; $tmpArr = [$token, $timestamp, $nonce]; // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if($tmpStr == $signature){ return true; }else{ return false; } } public function getSignPackage() { $jsapiTicket = $this->getJsApiTicket(); $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr = $this->createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url"; $signature = sha1($string); $signPackage = [ "appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ]; return $signPackage; } //获取微信授权url public function getUrlRedict($ref) { $queryParam = [ 'appid='.$this->appId, 'redirect_uri='.urlencode(Url::host().$this->redirectUrl.'?ref='.$ref), 'response_type=code', 'scope='.$this->scope, 'state=enter' ]; return $this->authUrlPrefix.join('&', $queryParam).'#wechat_redirect'; } public function getAuthInfo($code) { $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appId."&secret=".$this->appSecret."&code=".$code."&grant_type=authorization_code"; $openId = json_decode($this->https_request($url))->openid; $res = $this->getweChatInfo($openId); return $res; } private function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for($i = 0; $i < $length; $i++){ $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } private function getJsApiTicket() { // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例 $data = json_decode(file_get_contents("jsapi_ticket.json")); if(!empty($data) && $data->expire_time < time()){ $accessToken = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken"; $res = json_decode($this->httpGet($url)); $ticket = !empty($res)? $res->ticket: ''; if($ticket){ $data->expire_time = time() + 7000; $data->jsapi_ticket = $ticket; $fp = fopen("jsapi_ticket.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } }else{ $ticket = $data->jsapi_ticket; } return $ticket; } public function getUserSubscribe($openId) { $accessToken = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$accessToken}&openid={$openId}&lang=zh_CN"; $res = json_decode($this->https_request($url), true); return $res; } public function setWechat($appId, $appSecret) { $this->appId = $appId; $this->appSecret = $appSecret; } //通过openId拿到用户信息 public function getweChatInfo($openId) { $accessToken = $this->getAccessToken(); $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$accessToken.'&openid='.$openId.'&lang=zh_CN'; $res = json_decode($this->https_request($url, null)); return $res; } //获取临时二维码 public function getTemporaryQrcode($shopId) { $access_token = $this->getAccessToken(); $data = '{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$shopId.'}}}'; $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token; $result = json_decode($this->https_request($url, $data), true); $qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$result["ticket"]; return $qrcodeUrl; } //生成永久二维码 public function getForeverQrcode($agent_id) { $access_token = $this->getAccessToken(); $data = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": '.$agent_id.'}}}'; $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token; $result = json_decode($this->https_request($url, $data), true); $qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$result["ticket"]; return $qrcodeUrl; } //获取微信自定义菜单列表 public function getWechatMenuList() { $access_token = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=".$access_token; $res = json_decode($this->https_request($url)); return $res; } //创建微信自定义菜单 public function createWechatMenuList() { $data = file_get_contents("menu_list.json"); $access_token = $this->getAccessToken(); if(!empty($data)){ $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token; $res = $this->https_request($url, $data); return $res; }else{ return false; } } //发送文本消息 public function sendTextMessage($openid, $msg) { $access_token = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token; $data = '{"touser":"'.$openid.'","msgtype":"text", "text": { "content":"'.$msg.'" }'; $res = $this->https_request($url, $data); return $res; } //发送图片消息 public function sendImgMessage($openid, $media_id) { $access_token = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token; $data = '{"touser":"'.$openid.'","msgtype":"image", "image": { "media_id":"'.$media_id.'" }'; $res = $this->https_request($url, $data); return $res; } //返回素材列表 public function getAllMaterial($type, $offset, $count) { $access_token = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$access_token; $data = '{"type":"'.$type.'","offset":"'.$offset.'","count":"'.$count.'"}'; $res = $this->https_request($url, $data); return $res; } private function getAccessToken() { // access_token 应该全局存储与更新,以下代码以写入到文件中做示例 $data = json_decode(file_get_contents("../service/wechat/access_token.json", FILE_USE_INCLUDE_PATH)); if(!empty($data) && $data->expire_time < time()){ $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret; $res = json_decode($this->https_request($url)); $access_token = !empty($res)? $res->access_token: ''; if($access_token){ $data->expire_time = time() + 7000; $data->access_token = $access_token; $fp = fopen("access_token.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } }else{ $access_token = $data->access_token; } return $access_token; }

  

//微信上传临时素材
public function add_material($filename){
    $file_info=array(
        'filename'=> $filename,  //国片相对于网站根目录的路径
    );
    if (class_exists( 'CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
        $filedata = array (
            'fieldname' => new CURLFile ( realpath ( $file_info["filename"] ), 'image/jpeg' )
        );
    } else {
        $filedata = array (
            'fieldname' => '@' . realpath ( $file_info["filename"] )
        );
    }
    $url = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token='.$this->getAccessToken().'&type=image';
    $result = json_decode($this->https_request($url, $filedata));
    return $result;
}

  

/**
 * 生成UUID
 * 允许传入
 *
 * @param array  $default 默认的位置值
 * @param string $split 分隔符
 * @return string
 */
public static function uuid(array $default = [], $split = '')
{
    $partLength = [8, 4, 4, 4, 12];
    foreach($partLength as $i => $length){
        if(isset($default[$i])){
            $default[$i] = str_pad(substr($default[$i], 0, $length), $length, '0', STR_PAD_LEFT);
        }else{
            $default[$i] = '';
            while(strlen($default[$i]) < $length){
                $default[$i] .= str_pad(base_convert(mt_rand(0, 65535), 10, 16), 4, '0', STR_PAD_LEFT);
            }
        }
    }
    ksort($default);

    return implode($split, $default);
}

  

 /**
     * 移除UUID的分隔符
     * @param string $uuid 带分隔符-的UUID,36位
     * @return string 移除分隔符后的UUID,32位
     */
    public static function uuidSeparatorRemove($uuid){
        return str_replace('-', '', $uuid);
    }

    /**
     * 给UUID加上分隔符
     * @param string $uuid 不带分隔符-的UUID,32位
     * @return string 加上分隔符后的UUID,36位
     */
    public static function uuidSeparatorAdd($uuid){
        return self::insertStr($uuid, [8, 12, 16, 20], '-');
    }

  

/**
     * 在指定位置插入指定字符串
     * @param string $str 原字符串
     * @param int|array $offset 位置偏移量,单个或数组
     * @param string $input 插入的字符串
     * @return string 返回新的字符串
     */
    private static function insertStr($str, $offset, $input)
    {
        $newStr = '';
        for ($i = 0; $i < strlen($str); $i++){
            if (is_array($offset)){//如果插入是多个位置
                foreach ($offset as $v){
                    if ($i == $v){
                        $newStr .= $input;
                    }
                }
            }else{//直接是一个位置偏移量
                if ($i == $offset){
                    $newStr .= $input;
                }
            }
            $newStr .= $str[$i];
        }
        return $newStr;
    }

    /**
     * 生成密码
     *
     * @param string $pwd 密码明文
     * @param string $salt 扰乱因子
     * @return string
     */
    public static function encrypt($pwd, $salt)
    {
        return md5($salt.$pwd.$salt);
    }

    /**
     * 删除索引数组的键,转换为普通数组
     *
     * @param array $array 要转换的索引数组
     * @return array 转换后的普通数组
     */
    public static function delArrayAssoc($array)
    {
        $newArr = [];
        foreach($array as $value){
            $newArr[] = $value;
        }

        return $newArr;
    }

    /**
     * 解析JSON为数组,如果字符串为空,返回空数组
     *
     * @param $json
     * @return mixed
     */
    public static function decodeJSON($json)
    {
        if(is_string($json) && !empty($json)){
            return json_decode($json, true);
        }else{
            return [];
        }
    }

    /**
     * 将数据序列化成json,将不对中文进行编码
     *
     * @param $data
     * @return string
     */
    public static function encodeJSON($data)
    {
        if(is_string($data)){
            return $data;
        }else{
            return json_encode($data, JSON_UNESCAPED_UNICODE);
        }
    }

  

 /**
     * 平台类型
     *
     * @return string
     */
    public static function deviceType()
    {
        //获取USER AGENT
        $map   = [
            'pc'      => 'windows nt',
            'iphone'  => 'iphone',
            'ipad'    => 'ipad',
            'android' => 'android'
        ];
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach($map as $type => $flag){
            if(strpos($agent, $flag) !== false){
                return $type;
            }
        }

        return 'unknown';
    }

    /**
     * 判断是否为该终端
     *
     * @param string $flag MicroMessenger,
     *
     * @return bool
     */
    public static function isTheAgent($flag)
    {
        return (strpos($_SERVER['HTTP_USER_AGENT'], $flag) !== false);
    }

    /**
     * 简单属性映射,带索引的内容将进行映射
     *
     * @param array $map
     * @param array $data
     * @return array
     */
    public static function simpleMap($map, $data)
    {
        $list = [];
        foreach($map as $key => $value){
            if(is_int($key)){
                $key = $value;
            }
            if(isset($data[$key])){
                $list[$value] = $data[$key];
            }
        }

        return $list;
    }

    /**
     * 搜集属性列表,带索引的内容将进行映射,支持复杂的转换规则
     *
     * @param array $map
     * @param array $data
     * @param bool $ignoreEmpty
     * @return array
     */
    public static function map($map, $data, $ignoreEmpty = false)
    {
        $result     = [];
        $indexAssoc = false;
        foreach($map as $n => $v){
            if(is_int($n)){
                $n          = $v;
                $indexAssoc = true;
            }
            $type = 'string';
            preg_match('/^((.*))(.+)/', $n, $matched);
            if(count($matched) > 2){
                $type = $matched[1];
                $n    = $matched[2];
                if($indexAssoc){
                    $v = $n;
                }
            }
            $vns   = explode('.', $v);
            $value = $data;
            foreach($vns as $vn){
                if(isset($value[$vn])){
                    $value = $value[$vn];
                }elseif(substr($vn, 0, 1) === '"' && substr($vn, -1, 1) === '"'){
                    $value = substr($vn, 1, -1);
                }else{
                    $value = null;
                    break;
                }
            }
            if($value === null && $ignoreEmpty){
                continue;
            }
            switch($type){
                case 'int':
                    $value = intval($value?: 0);
                    break;
                case 'float':
                    $value = floatval($value?: 0);
                    break;
                case 'bool':
                    $value = boolval($value);
                    break;
                default:
                    $value = $value === null? '': $value;
                    break;
            }
            $result[$n] = $value;
        }

        return $result;
    }

    /**
     * 获取客户端IP,检查代理(代理通常可伪造)
     *
     * @return string
     */
    private static function getClientIp()
    {
        $ip = null;
        if(isset($_SERVER)){
            if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
                foreach($arr as $ip){
                    $ip = trim($ip);
                    if($ip != 'unknown'){
                        break;
                    }
                }
            }else{
                if(isset($_SERVER['HTTP_CLIENT_IP'])){
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
                }
            }
        }else{
            if(getenv('HTTP_X_FORWARDED_FOR')){
                $ip = getenv('HTTP_X_FORWARDED_FOR');
            }elseif(getenv('HTTP_CLIENT_IP')){
                $ip = getenv('HTTP_CLIENT_IP');
            }
        }
        if($ip === null){
            $ip = self::getShakeIp();
        }

        return $ip;
    }

    private static function getShakeIp()
    {
        return $_SERVER['REMOTE_ADDR']??getenv('REMOTE_ADDR')?: '0.0.0.0';
    }

    /**
     * 获取访客的IP地址
     *
     * @param bool $proxy 是否透过代理获取"真实IP"? 警告:该IP可以伪造
     * @param bool $long 返回的类型;true:将IP地址转换成整型返回;false:直接返回IP串
     * @return string||long
     */
    public static function getIp($proxy = true, $long = false)
    {
        if($proxy){
            /* 这类IP皆是可伪造的HTTP报文 */
            //此处为http报文,可伪造,不可靠
            $ip = self::getClientIp();
        }else{
            $ip = self::getShakeIp();
        }

        return $long? ip2long($ip): $ip;
    }

    /**
     * 将unicode数字编码转为字符
     *
     * @param $dec
     * @return string
     */
    public static function uniChr($dec)
    {
        if($dec < 128){
            $utf = chr($dec);
        }else{
            if($dec < 2048){
                $utf = chr(192 + (($dec - ($dec % 64)) / 64));
                $utf .= chr(128 + ($dec % 64));
            }else{
                $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
                $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
                $utf .= chr(128 + ($dec % 64));
            }
        }

        return $utf;
    }

    /**
     * 产生随机字符
     *
     * @param     $length
     * @param int $mask
     * @return string
     */
    public static function randString($length, $mask = JT_CHAR_NUMBER)
    {
        $randomString = "";
        $type         = [];
        foreach([1, 2, 4, 8] as $t){
            if($t & $mask){
                $type[] = $t;
            }
        }
        while($length){
            $c = '';
            switch($type[array_rand($type)]){
                case JT_CHAR_NUMBER:
                    $c = chr(mt_rand(48, 57));
                    break;
                case JT_CHAR_LOWERCASE:
                    $c = chr(mt_rand(97, 122));
                    break;
                case JT_CHAR_UPPERCASE:
                    $c = chr(mt_rand(65, 90));
                    break;
                case JT_CHAR_ZN_CH:
                    $c = self::uniChr(mt_rand(0x4e00, 0x9fa5));
                    break;
            }
            $randomString .= $c;
            $length--;
        }

        return $randomString;
    }

  

 /**
     * 获取当前网站所用的域名
     * @return string
     */
    public static function getDomain(){
        return $_SERVER['HTTP_HOST'];
    }

    /**
     * 绝对定位到当前主机
     * @return string
     */
    public static function getHost(){
        return 'http'.((isset($_SERVER['SERVER_PORT_SECURE']) && (int)$_SERVER['SERVER_PORT_SECURE'])?'s':'').'://'.$_SERVER['HTTP_HOST'];
    }

    /**
     * 获取当前访问页面的完整URL
     * @return string
     */
    public static function getUrl(){
        return 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
    }

    /**
     * 获取浏览器版本
     * @return string
     */
    public static function getBrowserVersion(){
        $httpUserAgent = $_SERVER["HTTP_USER_AGENT"];
        if(strpos($httpUserAgent, 'MSIE 8.0')){
            return 'IE8';
        }if(strpos($httpUserAgent, 'MSIE 9.0')){
            return 'IE9';
        }else if(strpos($httpUserAgent, 'MSIE 7.0')){
            return 'IE7';
        }else if(strpos($httpUserAgent, 'MSIE 6.0')){
            return 'IE6';
        }else if(strpos($httpUserAgent, 'Firefox/3')){
            return 'FIREFOX3';
        }else if(strpos($httpUserAgent, 'Firefox/2')){
            return 'FIREFOX2';
        }else if(strpos($httpUserAgent, 'Chrome')){
            return 'CHROME';
        }else if(strpos($httpUserAgent, 'Safari')){
            return 'SAFARI';
        }else if(strpos($httpUserAgent, 'Opera')){
            return 'OPERA';
        }else{
            return $httpUserAgent;
        }
    }

    /**
     * 获取浏览器名称
     * @return string
     */
    public static function getBrowser()
    {
        $userAgent = strtolower($_SERVER["HTTP_USER_AGENT"]);
        $browser   = "其他";

        //判断是否是myie
        if(strpos($userAgent, "myie")){
            $browser = "蚂蚁浏览器";
        }

        //判断是否是Netscape
        if(strpos($userAgent, "netscape")){
            $browser = "网景浏览器";
        }

        //判断是否是Opera
        if(strpos($userAgent, "opera")){
            $browser = "欧朋浏览器";
        }

        //判断是否是netcaptor
        if(strpos($userAgent, "netcaptor")){
            $browser = "netCaptor";
        }

        //判断是否是TencentTraveler
        if(strpos($userAgent, "tencenttraveler")){
            $browser = "腾讯TT浏览器";
        }

        //判断是否是微信浏览器
        if(strpos($userAgent, "micromessenger")){
            $browser = "微信浏览器";
        }

        //判断是否是QQ浏览器
        if(strpos($userAgent, "mqqbrowser")){
            $browser = "QQ浏览器";
        }

        //判断是否是UC浏览器
        if(strpos($userAgent, "ucbrowser") || strpos($userAgent, "ucweb")){
            $browser = "UC浏览器";
        }

        //判断是否是Firefox
        if(strpos($userAgent, "firefox")){
            $browser = "火狐浏览器";
        }

        //判断是否是ie
        if(strpos($userAgent, "msie") || strpos($userAgent, "trident")){
            $browser = "IE浏览器";
        }

        //判断是否是chrome内核浏览器
        if(strpos($userAgent, "chrome")){
            $browser = "谷歌浏览器";
        }

        return $browser;
    }

    /**
     * 获取用户USER_AGENT信息,判断终端平台系统
     * @return string
     */
    public static function getPlatform(){
        //$browserPlatform = '';
        $Agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(strstr($Agent, 'win') && strstr($Agent, 'nt 5.1')){
            $browserPlatform = "Windows XP";
        }elseif(strstr($Agent, 'win') && strstr($Agent, 'nt 6.1')){
            $browserPlatform = "Windows 7";
        }elseif(strstr($Agent, 'win') && strstr($Agent, 'nt 6.2')){
            $browserPlatform = "Windows 8";
        }elseif(strstr($Agent, 'win') && strstr($Agent, 'nt 6.3')){
            $browserPlatform = "Windows 8";
        }elseif(strstr($Agent, 'win') && strstr($Agent, 'nt 6.4')){
            $browserPlatform = "Windows 8";
        }elseif(strstr($Agent, 'win') && strstr($Agent, 'nt 10.0')){
            $browserPlatform = "Windows 10";
        }elseif(strstr($Agent, 'android')){
            $browserPlatform = "Android";
        }elseif(strstr($Agent, 'iphone')){
            $browserPlatform = "iPhone";
        }elseif(strstr($Agent, 'mac os')){
            $browserPlatform = "Mac OS";
        }elseif(strstr($Agent, 'ipad')){
            $browserPlatform = "iPad";
        }elseif(strstr($Agent, 'ipod')){
            $browserPlatform = "iPod";
        }elseif(strstr($Agent, 'linux')){
            $browserPlatform = "Linux";
        }elseif(strstr($Agent, 'unix')){
            $browserPlatform = "Unix";
        }elseif(strstr($Agent, 'win') && strstr($Agent, 'nt 6.0')){
            $browserPlatform = "Windows Vista";
        }elseif(strstr($Agent, 'win') && strstr($Agent, '32')){
            $browserPlatform = "Windows 32";
        }elseif(strstr($Agent, 'win') && strstr($Agent, '95')){
            $browserPlatform = "Windows 95";
        }elseif(strstr($Agent, 'win') && strstr($Agent, '98')){
            $browserPlatform = "Windows 98";
        }elseif(strstr($Agent, 'win') && strstr($Agent, 'nt 5.0')){
            $browserPlatform = "Windows 2000";
        }elseif(strstr($Agent, 'win') && strstr($Agent, 'nt')){
            $browserPlatform = "Windows NT";
        }elseif(strstr($Agent, 'win 9x') && strstr($Agent, '4.90')){
            $browserPlatform = "Windows ME";
        }elseif(strstr($Agent, 'sun') && strstr($Agent, 'os')){
            $browserPlatform = "SunOS";
        }elseif(strstr($Agent, 'ibm') && strstr($Agent, 'os')){
            $browserPlatform = "IBM OS/2";
        }elseif(strstr($Agent, 'mac') && strstr($Agent, 'pc')){
            $browserPlatform = "Macintosh";
        }elseif(strstr($Agent, 'powerpc')){
            $browserPlatform = "PowerPC";
        }elseif(strstr($Agent, 'aix')){
            $browserPlatform = "AIX";
        }elseif(strstr($Agent, 'hpux')){
            $browserPlatform = "HPUX";
        }elseif(strstr($Agent, 'netbsd')){
            $browserPlatform = "NetBSD";
        }elseif(strstr($Agent, 'bsd')){
            $browserPlatform = "BSD";
        }elseif(strstr($Agent, 'osf1')){
            $browserPlatform = "OSF1";
        }elseif(strstr($Agent, 'irix')){
            $browserPlatform = "IRIX";
        }elseif(strstr($Agent, 'freebsd')){
            $browserPlatform = "FreeBSD";
        }else{
            $browserPlatform = "Other";
        }

        return $browserPlatform;
    }

    /**
     * 根据时间戳获取指定某天起止时间戳
     * @param string $time 当天任意时间戳
     * @param int $range 前后天数,如后一天为1,前一天为-1
     * @return array [开始时间,结束时间]
     */
    public static function getDayRangeTime($time = null, $range = 0){
        $time = $time ? $time : RUN_START_TIME;
        $y = date('Y', $time);
        $m = date('m', $time);
        $d = date('d', $time) + $range;
        return [mktime(0, 0, 0, $m, $d, $y), mktime(23, 59, 59, $m, $d, $y)];
    }

    /**
     * 根据时间戳获取周起止时间戳
     * @param string $time 当天任意时间戳
     * @param int $range 前后周数,如下周+1,上周-1
     * @return array [开始时间,结束时间]
     */
    public static function getWeekRangeTime($time = null, $range = 0){
        $time = $time ? $time : RUN_START_TIME;
        $y = date('Y', $time);
        $m = date('m', $time);
        $d = date('d', $time);
        $w = date('w', $time) + $range;
        return [mktime(0, 0, 0, $m, $d-$w+1, $y), mktime(23, 59, 59, $m, $d-$w+7, $y)];
    }

    /**
     * 根据时间戳获取指定月份起止时间戳
     * @param string $time 当月任意时间戳
     * @param int $range 前后月份数,如后一月为1,前一月为-1
     * @return array [开始时间,结束时间]
     */
    public static function getMonthRangeTime($time = null, $range = 0){
        $time = $time ? $time : RUN_START_TIME;
        $y = date('Y', $time);
        $m = date('m', $time) + $range;
        return [mktime(0, 0, 0, $m, 1, $y), mktime(0, 0, 0, $m+1, 1, $y)-1];
    }

  

//h5和Android,ios交互
appPrint: (data) =>{
    if(window.BridgeToAndroid){
        let dataStr = JSON.stringify(data);
        window.BridgeToAndroid.printReceipt(dataStr);
        return false;
    }
    if(window.WebViewJavascriptBridge){
        window.WebViewJavascriptBridge.send({"tag": "printReceipt", "value": data});
        return false;
    }else{
        document.addEventListener('WebViewJavascriptBridgeReady', function(){
            window.WebViewJavascriptBridge.send({"tag": "printReceipt", "value": data});
            return false;
        }, false);
    }
}

//url为请求的地址,data为请求发送的数据,如果data为空,则为get请求
public function https_request($url, $data = null)
{
    $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;
}

  

原文地址:https://www.cnblogs.com/huangguojin/p/6769625.html