如题,curl各种操作,封装为一个方法,一劳永逸
话不多说,直接上代;不能使用,提棍找我
1 <?php 2 /** 3 * 发送http请求 4 * @param string $url 请求地址 5 * @param string $method http方法(GET POST PUT DELETE) 6 * @param array $data http请求数据 7 * @param array $header http请求头 8 * @param Int $type 请求数据类型 0-array 1-jason 9 * @return string|bool 10 */ 11 function send_request($url, $method = "POST", $data = array(), $header = array(), $type = '0') { 12 //检查地址是否为空 13 if (empty($url)) { 14 return false; 15 } 16 //控制请求方法范围 17 $httpMethod = array('GET', 'POST', 'PUT', 'DELETE'); 18 $method = strtoupper($method); 19 if (!in_array($method, $httpMethod)) { 20 return false; 21 } 22 //请求头初始化 23 $request_headers = array(); 24 $User_Agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31'; 25 $request_headers[] = 'User-Agent: '. $User_Agent; 26 if($header){ 27 foreach ($header as $v) { 28 $request_headers[] = $v; 29 } 30 } 31 32 $request_headers[] = 'Accept: text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; 33 switch ($method) { 34 case "POST": 35 $request_headers[] = "X-HTTP-Method-Override: POST"; 36 break; 37 case "PUT": 38 $request_headers[] = "X-HTTP-Method-Override: PUT"; 39 break; 40 case "DELETE": 41 $request_headers[] = "X-HTTP-Method-Override: DELETE"; 42 break; 43 default: 44 } 45 //发送http请求 46 $ch = curl_init(); 47 curl_setopt($ch, CURLOPT_URL, $url); 48 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 49 curl_setopt($ch, CURLOPT_HEADER, false); 50 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//https 51 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 52 curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers); 53 switch ($method) { 54 case "POST": 55 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 56 break; 57 case "PUT": 58 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); 59 break; 60 case "DELETE": 61 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); 62 break; 63 default: 64 } 65 66 //格式化发送数据 67 if($data) { 68 if ($type) { 69 $dataValue = json_encode($data,JSON_UNESCAPED_UNICODE); 70 }else{ 71 $dataValue = http_build_query($data); 72 } 73 curl_setopt($ch, CURLOPT_POSTFIELDS, $dataValue); 74 } 75 76 curl_setopt($ch, CURLOPT_TIMEOUT, 50); 77 //发送请求获取返回响应 78 $result['data'] = curl_exec($ch); 79 $result['httpCode'] = curl_getinfo($ch,CURLINFO_HTTP_CODE); 80 if(strlen(curl_error($ch))>1){ 81 $result = false; 82 } 83 84 curl_close($ch); 85 return $result; 86 } 87 88 ?>