每日笔记

记录击毙


curl类库(post、get、json)请求

<pre><code>&lt;?php /** * Created by PhpStorm. * User: 18110 * Date: 2018/12/14 * Time: 18:47 */ class Curl { /** * post请求 * @param $url * @param array $post_data * @param string $msg * @return mixed */ public function requestPost($url , $post_data = array() , $msg = ''){ // 1. 初始化一个cURL会话 $ch = curl_init(); // 2. 设置请求选项, 包括具体的url curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设置请求为post类型 curl_setopt($ch, CURLOPT_POST, 1); // 添加post数据到请求中 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); curl_setopt($ch, CURLOPT_HEADER, 0); // 3. 执行一个cURL会话并且获取相关回复 $response = curl_exec($ch); //$response = json_decode($response,true); if ($response === FALSE) { if ($msg == ''){ logMessage('error','curl请求发送失败!失败信息:'.curl_error($ch)); }else{ logMessage('error' , $msg.'失败信息:'.curl_error($ch)); } } // 4. 释放cURL句柄,关闭一个cURL会话 curl_close($ch); return $response; } /** * get请求 * @param $url * @param string $msg * @return mixed */ public function requestGet($url , $msg = ''){ // 1. 初始化一个cURL会话 $ch = curl_init(); //设置选项,包括URL curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); //执行并获取HTML文档内容 $response = curl_exec($ch); if ($response === FALSE) { if ($msg == ''){ logMessage('error','curl请求发送失败!失败信息:'.curl_error($ch)); }else{ logMessage('error' , $msg.'失败信息:'.curl_error($ch)); } } // 4. 释放cURL句柄,关闭一个cURL会话 curl_close($ch); return $response; } /** * json请求 * @param $url * @param $json_data * @param string $msg */ public function requestJson($url , $json_data , $msg = ''){ if (!is_array($json_data)){ return false; } $data = json_encode($json_data); $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json")); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //执行并获取HTML文档内容 $response = curl_exec($ch); if ($response === FALSE) { if ($msg == ''){ logMessage('error','curl请求发送失败!失败信息:'.curl_error($ch)); }else{ logMessage('error' , $msg.'失败信息:'.curl_error($ch)); } } // 4. 释放cURL句柄,关闭一个cURL会话 curl_close($ch); return $response; } }</code></pre>

页面列表

ITEM_HTML