常用封装curl函数
/** * curl类,get方式提交数据到指定url * @param $url: 提交数据的地址 * @param @data: 提交的数据 * @return json */ function httpGet($url){ $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//在服务器还没有开启https验证的时候跳过验证 $res = curl_exec($curl); curl_close($curl); return $res; } /** * post提交信息到地址(application/x-www-form-urlencoded方式) * @param $url: 提交数据的地址 * @param $data: 提交的数据 * @param $useCert:包含证书路径的数组,如果存在则启用证书 * @return json */ function httpPost($url,$data,$useCert=''){ // echo ."````".dirname(dirname(__FILE__));exit; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.33 Safari/537.36'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_AUTOREFERER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); if($data != ""){ curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } if(!empty($useCert)){ //设置证书 //使用证书:cert 与 key 分别属于两个.pem文件 curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM'); curl_setopt($ch,CURLOPT_SSLCERT, $useCert['apiclient_cert']); curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM'); curl_setopt($ch,CURLOPT_SSLKEY, $useCert['apiclient_key']); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $tmpInfo = curl_exec($ch); if (curl_errno($ch)) { return ("curl_error: ".curl_error($ch)); } curl_close($ch); return $tmpInfo; }
又一个封装curl函数
//把请求发送到微信服务器换取二维码 // $result = httpRequest( $url, $param_json_arr ,"POST"); function httpRequest($url, $data='', $method='GET'){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_AUTOREFERER, 1); if($method=='POST') { curl_setopt($curl, CURLOPT_POST, 1); if ($data != '') { curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } } curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); return $result; }
添加cookie
$cookie_file = dirname(__FILE__) . '/cookie.txt'; curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);