PHP取得HTTP請求的原文____PHP

來源:互聯網
上載者:User

轉載自:http://www.veryhuo.com/a/view/34557.html

1. 取得請求行:Method、URI、協議 

可以從超級變數$_SERVER中獲得,三個變數的值如下: 

$_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\r\n"; 
2. 取得所有Header 

PHP有個內建函數getallheader(),是apache_request_headers()函數的一個別名,可以將HTTP請求的所有Header以數組形式返回。但這個函數只能工作在Apache下,如果換了Nginx或者命令列,會直接報函數不存在的錯誤。 

比較通用的方法是,從超級變數$_SERVER中提取出來,有關Header的索引值都是“HTTP_”開頭的,可以根據此特點取得所有的Header。代碼如下: 

function get_all_headers() { 
$headers = array(); 

foreach($_SERVER as $key => $value) { 
if(substr($key, 0, 5) === 'HTTP_') { 
$key = substr($key, 5); 
$key = strtolower($key); 
$key = str_replace('_', ' ', $key); 
$key = ucwords($key); 
$key = str_replace(' ', '-', $key); 

$headers[$key] = $value; 



return $headers; 

3. 取得Body 

官方提供了一種擷取請求Body的方法,即: 

file_get_contents('php://input') 
4. 最終代碼 

/** 
* 擷取HTTP請求原文 
* @return string 
*/ 
function get_http_raw() { 
$raw = ''; 

// (1) 請求行 
$raw .= $_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\r\n"; 

// (2) 請求Headers 
foreach($_SERVER as $key => $value) { 
if(substr($key, 0, 5) === 'HTTP_') { 
$key = substr($key, 5); 
$key = str_replace('_', '-', $key); 

$raw .= $key.': '.$value."\r\n"; 



// (3) 空行 
$raw .= "\r\n"; 

// (4) 請求Body 
$raw .= file_get_contents('php://input'); 

return $raw; 
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.