资讯专栏INFORMATION COLUMN

php常用函数集合

jay_tian / 912人阅读

摘要:操作方式方式去除跨域脚本攻击中文转码判断参数是否为空判断是否为数组用来处理不是数组的情况用来处理数组用来处理数组返回微信获取授权第一步取得第二步根据全局和查询用户信息给微信用户发送文字消息导出表格兑换列表导出表格是否下载表格第一列

1.curl操作

POST方式

public static function httpPost($url, $param = "")
{
    $ch1 = curl_init();
    if (version_compare(PHP_VERSION, "5.5.0", ">")) {
        curl_setopt($ch1, CURLOPT_SAFE_UPLOAD, false);
    }

    curl_setopt($ch1, CURLOPT_URL, $url);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($param)) {
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $param);
    }
    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch1);
    curl_close($ch1);
    return $result;
}

GET方式

public static function httpGet($url)
{
    $oCurl = curl_init();
    if (stripos($url, "https://") !== false) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    $sContent = curl_exec($oCurl);
    $aStatus  = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

2.去除跨域脚本攻击

public static function removeXSS($val)
{
    $val    = preg_replace("/([x00-x08,x0b-x0c,x0e-x19])/", "", $val);
    $search = "abcdefghijklmnopqrstuvwxyz";
    $search .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $search .= "1234567890!@#$%^&*()";
    $search .= "~`";:?+/={}[]-_|"";
    for ($i = 0; $i < strlen($search); $i++) {
        $val = preg_replace("/(&#[xX]0{0,8}" . dechex(ord($search[$i])) . ";?)/i", $search[$i], $val);
        $val = preg_replace("/(�{0,8}" . ord($search[$i]) . ";?)/", $search[$i], $val);
    }

    $ra1 = array("javascript", "vbscript", "expression", "applet", "meta", "xml", "blink", "link", "style", "script", "embed", "object", "iframe", "frame", "frameset", "ilayer", "layer", "bgsound", "title", "base");
    $ra2 = array("onabort", "onactivate", "onafterprint", "onafterupdate", "onbeforeactivate", "onbeforecopy", "onbeforecut", "onbeforedeactivate", "onbeforeeditfocus", "onbeforepaste", "onbeforeprint", "onbeforeunload", "onbeforeupdate", "onblur", "onbounce", "oncellchange", "onchange", "onclick", "oncontextmenu", "oncontrolselect", "oncopy", "oncut", "ondataavailable", "ondatasetchanged", "ondatasetcomplete", "ondblclick", "ondeactivate", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "onerror", "onerrorupdate", "onfilterchange", "onfinish", "onfocus", "onfocusin", "onfocusout", "onhelp", "onkeydown", "onkeypress", "onkeyup", "onlayoutcomplete", "onload", "onlosecapture", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onmove", "onmoveend", "onmovestart", "onpaste", "onpropertychange", "onreadystatechange", "onreset", "onresize", "onresizeend", "onresizestart", "onrowenter", "onrowexit", "onrowsdelete", "onrowsinserted", "onscroll", "onselect", "onselectionchange", "onselectstart", "onstart", "onstop", "onsubmit", "onunload");
    $ra  = array_merge($ra1, $ra2);

    $found = true;
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = "/";
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= "(";
                    $pattern .= "(&#[xX]0{0,8}([9ab]);)";
                    $pattern .= "|";
                    $pattern .= "|(�{0,8}([9|10|13]);)";
                    $pattern .= ")*";
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= "/i";
            $replacement = substr($ra[$i], 0, 2) . "" . substr($ra[$i], 2);
            $val         = preg_replace($pattern, $replacement, $val);
            if ($val_before == $val) {
                $found = false;
            }
        }
    }
    return $val;
}    

3.JSON中文转码

public static function cn_arr_json($arr)
{
    $_var = self::var_urlencode($arr);
    $_str = json_encode($_var);
    return urldecode($_str);
}
public static function var_urlencode($var)
{
    if (empty($var)) {return false;} //判断参数是否为空
    if (is_array($var)) {
        //判断是否为数组
        foreach ($var as $k => $v) {
            if (is_scalar($v)) {
                //if用来处理不是数组的情况
                $var[$k] = urlencode($v);
            } else {
                $var[$k] = self::var_urlencode($v); //else用来处理数组
            }
        }
    } else {
        $var = urlencode($var); //用来处理数组
    }
    return $var;
}    

4.ajax返回

public function ajaxJson($state = "success",$msg = "",$params = ""){
    $json = array();
    if($msg){$json["msg"] = $msg;}
    if($params){
        if(is_array($params)){
            foreach($params as $key => $val){
                $json[$key] = $val;
            }
        }else{
            $json["p"] = $params;
        }
    }
    $json["state"] = $state;
    echo json_encode($json);exit;
}  

5.微信获取授权
function _diy_wxauth($authurl, $scope = "snsapi_base")
{

$appid=XUETANG_APPID;
$secret = XUETANG_SCRECT;
$code = isset($_GET["code"])?$_GET["code"]:"";
if($code){

//第一步:取得openid

    $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
    $oauth2 = getJson($oauth2Url);

//第二步:根据全局access_token和openid查询用户信息

    $access_token = $oauth2["access_token"];
    $openid = $oauth2["openid"];
    $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
    return getJson($get_user_info_url);
}else{
    $redirect_uri = urlencode( WEBSITEURL.$authurl);
    $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=$scope&state=123#wechat_redirect";
    header("Location:".$url);
}

}
//给微信用户发送文字消息
function replyhreftxt($openid, $txt)
{

$access_token = getDxToken();
$url          = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $access_token;
if ($openid && $txt) {
    $datajson = "{"touser":"" . $openid . "","msgtype":"text","text":{"content":"" . $txt . ""}}";
    $res      = http_post($url, $datajson);
    if ($res) {
        return true;
    } else {
        return false;
    }
} else {
    return false;
}

}
6.PHPExcel导出Excel表格
/* 兑换列表导出Excel表格
$isDown 是否下载
$title 表格第一列
$data 需要导出的数据
$filename 文件名
*/

public function actionExceldata()
{
    $isDown=true;
    $fileName = "兑换列表";
    $title = [0=>"用户名",1=>"手机号",2=>"添加时间",3=>"状态","标题"];
    $getPar = $this->params->get();
    $this->exchangeModels->setParams($getPar);
    $data = $this->exchangeModels->getAll();
    foreach ($data as $k => $v){
        if($v["state"] == 1){
            $data[$k]["state"] = "未发放";
        }elseif($v["state"] == 2){
            $data[$k]["state"] = "待发送";
        }else{
            $data[$k]["state"] = "已发放";
        }
    }
    require($_SERVER["DOCUMENT_ROOT"]."/../../vendor/PHPExcel-1.8/Classes/PHPExcel.php");
    require($_SERVER["DOCUMENT_ROOT"]."/../../vendor/PHPExcel-1.8/Classes/PHPExcel/IOFactory.php");
    $obj = new PHPExcel();
    //横向单元格标识
    $cellName = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ");
    $obj->getActiveSheet(0)->setTitle("sheet名称");   //设置sheet名称
    $_row = 1;   //设置纵向单元格标识
    if($title){
        $_cnt = count($title);
        $obj->getActiveSheet(0)->mergeCells("A".$_row.":".$cellName[$_cnt-1].$_row);   //合并单元格
        $obj->setActiveSheetIndex(0)->setCellValue("A".$_row, "数据导出:".date("Y-m-d H:i:s"));  //设置合并后的单元格内容
        $_row++;
        $i = 0;
        foreach($title AS $v){   //设置列标题
            $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
            $i++;
        }
        $_row++;
    }
    //填写数据
    if($data){
        $i = 0;
        foreach($data AS $_v){
            $j = 0;
            foreach($_v AS $_cell){
                $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
                $j++;
            }
            $i++;
        }
    }
    //文件名处理
    if(!$fileName){
        $fileName = uniqid(time(),true);
    }
    $objWrite = PHPExcel_IOFactory::createWriter($obj, "Excel2007");
    if($isDown){   //网页下载
        header("pragma:public");
        header("Content-Disposition:attachment;filename=$fileName.xls");
        $objWrite->save("php://output");exit;
    }
    /*$_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
    $_savePath = $savePath.$_fileName.".xlsx";
    $objWrite->save($_savePath);exit;*/
    //return $savePath.$fileName.".xlsx";
}

//导出数据,但是不是Excel表格,优点:导出的数据量比较大
*@param $datas array 设置表格数据
*@param $titlename string 设置head
*@param $title string 设置表头
*/

public function excelData($datas,$titlename,$title,$filename){
$str = "rnrnrnrn";
$str .="

".$titlename."";
$str .= $title;
foreach ($datas as $key=> $rt )
{
$str .= "";
foreach ( $rt as $k => $v )
{
$str .= "";
}
$str .= "n";
}
$str .= "
{$v}
";
header( "Content-Type: application/vnd.ms-excel; name="excel"" );
header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename=".$filename );
header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
header( "Pragma: no-cache" );
header( "Expires: 0" );
exit( $str );
}
//导出Excel,无插件
public function actionExportindexdetail()

{
    $this->GiftdetailModels->setParams($this->params->get());
    $list = $this->GiftdetailModels->getAllList();
    $str = "用户名称,礼品,礼品码,礼品对应密码,使用积分,兑换时间
";
    $str = iconv("utf-8","gb2312",$str);
    foreach($list as $row){
        $nickname = iconv("UTF-8", "GB2312//IGNORE",$row["nickname"]);
        $giftname = iconv("UTF-8", "GB2312//IGNORE",$row["giftname"]);
        $gnumber = iconv("UTF-8", "GB2312//IGNORE",$row["gnumber"]);
        $gmima = iconv("UTF-8", "GB2312//IGNORE",$row["gmima"]);
        $usescore = iconv("UTF-8", "GB2312//IGNORE",$row["usescore"]);
        $addtime = iconv("UTF-8", "GB2312//IGNORE", date("Y-m-d H:i:s",$row["addtime"]));
        $str .= $nickname.",".$giftname.",".$gnumber.",".$gmima.",".$usescore.",".$addtime."
";
    }
    $filename = "兑换管理_".date("YmdHis").".csv"; //设置文件名
    export_csv($filename,$str); //导出
}

public static function export_csv($filename,$data) {

    header("Content-type:text/csv"); 
    header("Content-Disposition:attachment;filename=".$filename); 
    header("Cache-Control:must-revalidate,post-check=0,pre-check=0"); 
    header("Expires:0"); 
    header("Pragma:public"); 
    echo $data; 
} 

7.生成随机验证码
function getCode()
{

$str = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
return substr(str_shuffle($str),26,10);

}
8.判断手机号归属地
function phoneCity($account)
{

$url = "http://202.102.221.75:18085/wxservice/hd.jsp";
$serverSign = MD5($account."$"."TTMM%S%XXYY");
$param = array(
    "account" => $account,
    "sign" => $serverSign,
);
$res = CurlPost($url, $param);
$newArr = json_decode($res,true);
return $newArr["ContractRoot"]["SvcCont"]["SOO"][0]["PHONE_LATN_TYPE_RES"][0]["LATN_ID"];

}
9.成功或失败返回ajax

/**
 * 将错误信息返回给Ajax请求
 * @param string $msg 错误信息描述
 * @param integer $code 错误代码,默认1
 */
public function ajaxError($msg = "", $code = 1)
{
    $this->ajaxEcho([
        "error" => $code,
        "msg" => $msg,
    ]);
}

/**
 * 将成功信息返回给Ajax请求
 * @param mix $data 返回数据
 */
public function ajaxSuccess($data = "")
{
    $this->ajaxEcho([
        "error" => 0,
        "data" => $data,
    ]);
}

/**
 * 一般情况下直接使用ajaxSuccess和ajaxError可以满足绝大部分需求
 * 考虑灵活性,本函数设置为公开,以满足特殊需求
 */
public function ajaxEcho($arr)
{
    header("Content-type:application/json;charset=utf-8");
    echo json_encode($arr);
    exit;
}

10.正则表达式

function regex($value,$rule) {
    $validate = array(
            "require"   =>  "/S+/",
            "email"     =>  "/^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$/",
            "url"       =>  "/^http(s?)://(?:[A-za-z0-9-]+.)+[A-za-z]{2,4}(?:[/?#][/=?%-&~`@[]":+!.#w]*)?$/",
            "currency"  =>  "/^d+(.d+)?$/",
            "number"    =>  "/^d+$/",
            "qq"        =>  "/^d*$/",
            "telephone" =>  "/^0([1-9]{3})([0-9]{7,8})$/",
            "zip"       =>  "/^d{6}$/",
            "integer"   =>  "/^[-+]?d+$/",
            "double"    =>  "/^[-+]?d+(.d+)?$/",
            "english"   =>  "/^[A-Za-z]+$/",
            "mobile"    =>  "/^1[3-9]{1}[0-9]{1}[0-9]{8}$/",
    );
    // 检查是否有内置的正则表达式
    if(isset($validate[strtolower($rule)]))
        $rule       =   $validate[strtolower($rule)];
    return preg_match($rule,$value)===1;
}    

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/29789.html

相关文章

  • 十五个常用的 Laravel 集合(Collection)

    摘要:将返回通过回调真值测试的第一个项的键。方法将集合分割为多个给定大小的较小集合。它可用于在任何位置的调试和查找集合内的内容。方法用于遍历整个集合。这对集合同样有效。它将导致由第二个参数的值作为键的集合。它接受回调并传递并将集合传递给它。 showImg(https://segmentfault.com/img/remote/1460000018924972); 文章转自:https://...

    alphahans 评论0 收藏0
  • PHP标准库SPL学习之数据结构、常用迭代器、基础接口

    摘要:将数组或者集合中的全部或者一部数据取出来,用迭代器比较方便迭代器能陆续遍历几个迭代器按顺序迭代访问几个不同的迭代器。 一、SPL简介      什么是SPL PHP的标准库SPL:Standard PHP Library      SPL: 用于解决常见普遍问题的一组接口与类的集合      Common Problem: 数学建模/数据结构 解决数据怎么存储的问题 元素遍历 ...

    2i18ns 评论0 收藏0
  • 带你入门 JavaScript ES6 (五) 集合

    摘要:一概述集合是引入的新的内置对象类型,其特点同数学意义的集合,即集合内所有元素不重复元素唯一。数组集合对比数组和集合,数组可以加入重复数据,而集合的所有元素是唯一的不允许重复。因此,适合临时存放一组对象,以及存放跟对象绑定的信息。 本文同步带你入门 带你入门 JavaScript ES6 (五) 集合,转载请注明出处。 前面我们学习了: for of 变量和扩展语法 块作用域变量和解构...

    BetaRabbit 评论0 收藏0
  • 你可能需要了解下Laravel集合

    摘要:前言集合通过进行实例,的内核大部分的参数传递都用到了集合,但这并不代表集合就是好的。当你需要处理一组数组时,你可能就需要它帮助你快捷的解决实际问题。例如我们需要通过一个水平线切分数组,将其分为个及以上的数组个数。谢谢,还不抓紧去练习下集合 showImg(https://segmentfault.com/img/bVbhjvY?w=600&h=296); 前言 集合通过 Illumin...

    fuyi501 评论0 收藏0
  • PHP 进阶之路 - 后端多元化之快速切入 Java 开发

    摘要:以实现自己熟悉的东西为导向比如我们做后端开发,首先是常用的循环迭代条件判断增删改成。它是由实现的,不保证元素的顺序,也就是说所说元素插入的顺序与输出的顺序不一致。 下面是我直播的文字版,直播地址:https://segmentfault.com/l/15...代码:https://github.com/zhoumengka...整个项目我们我又细分了6个版本来演进,希望更加便于大家对比...

    Cristic 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<