php常用函数集合
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) . '<x>' . 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 = "<html xmlns:o="urn:schemas-microsoft-comoffice"rnxmlns:x="urn:schemas-microsoft-comexcel"rnxmlns="http://www.w3.org/TR/REC-html40">rn<head>rn<meta http-equiv=Content-Type content="text/html; charset=utf-8">rn</head>rn<body>";
$str .="<table border=1><head>".$titlename."</head>";
$str .= $title;
foreach ($datas as $key=> $rt )
{
$str .= "<tr>";
foreach ( $rt as $k => $v )
{
$str .= "<td>{$v}</td>";
}
$str .= "</tr>n";
}
$str .= "</table></body></html>";
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 = "用户名称,礼品,礼品码,礼品对应密码,使用积分,兑换时间\n"; $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."\n"; } $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; }