1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| <?php function httpRequest($url, $method, $headers, $body=NULL){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); switch ($method) { case "POST": if ($body != NULL){ curl_setopt($ch, CURLOPT_POSTFIELDS, $body); $bodyLength = strlen($body); $headers[] = "content-length: $bodyLength"; } default: break; } curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate'); curl_setopt($ch, CURLOPT_HEADER, TRUE); curl_setopt($ch, CURLOPT_NOBODY, FALSE); curl_setopt($ch, CURLOPT_NOSIGNAL, 1); curl_setopt($ch, CURLOPT_TIMEOUT_MS, 300); $resp = curl_exec($ch); $respStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); $respHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $respHeaders = substr($resp, 0, $respHeaderSize); $respBody = substr($resp, $respHeaderSize); curl_errno($ch); curl_close($ch); return array( "status"=>$respStatus, "headers"=> headerStrHandler($respHeaders), "body"=>$respBody ); }
function headerStrHandler($headerStr) { $headerLines = explode("\n", $headerStr); $headers = array(); foreach($headerLines as $headerLine) { $header = explode(": ", $headerLine); if (count($header) > 1) { $headers[trim($header[0])] = trim($header[1]); } } return $headers; }
$url = "https://www.baidu.com"; $method = $_SERVER["REQUEST_METHOD"]; $headers = array(); foreach (getallheaders() as $key => $value) { if (strtolower($key) == "accept") { $headers["accept"] = $value; } if (strtolower($key) == "content-type") { $headers[] = "content-type: $value"; } } $headers[] = "user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 UOS";
$body = file_get_contents("php://input");
if ($method == "OPTIONS") { http_response_code(200); header("access-control-allow-headers: *"); header("access-control-allow-origin: *"); header("content-type: text/html"); die(); }
http_response_code(200); header("access-control-allow-headers: *"); header("access-control-allow-origin: *"); header("content-type: application/json; charset=utf-8"); $response = httpRequest($url, $method, $headers, $body);
echo $response["body"];
|
v1.5.2