/** * 发送https/http请求 正常/异步 * @param string $url 请求地址 * @param array $params http请求数据, 数据类型必须是Array * @param string $method http方法(GET POST PUT DELETE) * @param array $header http请求头 * @param int $type 请求类型 0正常,1异步 * @return string|bool */ function request_curl($url, $params = [], $method = "POST", $header = [], $type = 0) { //检查地址是否为空 if (empty($url)) { return false; } //控制请求方法范围 $httpMethod = array('GET', 'POST', 'PUT', 'DELETE'); $method = strtoupper($method); if (!in_array($method, $httpMethod)) { return false; } //请求头初始化 $request_headers = array(); $User_Agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31'; $request_headers[] = 'User-Agent: '. $User_Agent; if($header){ foreach ($header as $v) { $request_headers[] = $v; } } $request_headers[] = 'Accept: text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; switch ($method) { case "POST": $request_headers[] = "X-HTTP-Method-Override: POST"; break; case "PUT": $request_headers[] = "X-HTTP-Method-Override: PUT"; break; case "DELETE": $request_headers[] = "X-HTTP-Method-Override: DELETE"; break; default: } //格式化发送数据 if($params) { if($method == 'GET'){ //GET请求 $url = $url . '?' . http_build_query($params); } /*else{ if (!$type){ $params = json_encode($params,JSON_UNESCAPED_UNICODE); } }*/ } //发送http请求 $ch = curl_init(); if($type) { curl_setopt($ch, CURLOPT_TIMEOUT, 1);//设置超时时间为1秒,超过1秒则关闭连接 curl_setopt($ch, CURLOPT_NOSIGNAL, 1); //注意,毫秒超时一定要设置这个 curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200); //超时毫秒,cURL 7.16.2中被加入。从PHP 5.2.3起可使用 }else{ curl_setopt($ch, CURLOPT_TIMEOUT, 1500); // 最大执行时间 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1500); // 在尝试连接时等待的秒数 } curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址 curl_setopt($ch, CURLOPT_HEADER, 0);// 设置是否显示返回头信息 1返回 0不返回 curl_setopt($ch, CURLOPT_NOBODY, 0); //不想在输出中包含body部分,设置这个选项为一个非零值 curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回 curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//https 不进行ssl验证 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);//设置头信息 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式 if($method != 'GET'){ if($method != 'POST'){ curl_setopt($ch, CURLOPT_POST, TRUE); } curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } //发送请求获取返回响应 $result['data'] = curl_exec($ch); $result['httpCode'] = curl_getinfo($ch,CURLINFO_HTTP_CODE); $error = curl_error($ch); if($error){ $result['data'] = $error; } curl_close($ch); return $result; } //用法举例 $params = array( 'input_text' => 'PHP用CURL发送请求' ); $header = ['Content-Type: application/x-www-form-urlencoded; charset=UTF-8', 'Referer: https://ken.01h.net/']; $result = request_curl('https://ken.01h.net/receive.php', $params, 'POST', $header, 0); print_r($result);
分类:PHP
PHP开发