2012-12-20 57 views
2

我想讓服務器端POST在PHP中工作。我想交易數據發送到支付網關,但我不斷收到以下錯誤:PHP服務器端帖子

Message: fopen(https://secure.ogone.com/ncol/test/orderstandard.asp) : failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required

代碼:

$opts = array(
    'http' => array(
     'Content-Type: text/html; charset=utf-8', 
     'method' => "POST", 
     'header' => "Accept-language: en\r\n" . 
     "Cookie: foo=bar\r\n" 
    ) 
); 

$context = stream_context_create($opts); 

$fp = fopen('https://secure.ogone.com/ncol/test/orderstandard.asp', 'r', false, $context); 
fpassthru($fp); 
fclose($fp); 

試過在網上找到了幾個解決方案 - 主要是投在黑暗中所以沒有運氣至今!

+4

我認爲這個錯誤意味着你必須包含'Content-length'頭部。計算提交的數據中的字節數幷包含此標題。 –

+0

感謝您的回覆 - 是將此信息寫入文件,獲取文件大小並使用此值的最佳方式? –

+0

你的POST數據在哪裏? –

回答

3

只需添加內容的長度。一旦你真的開始發送內容,你需要計算它的長度。

$data = ""; 
$opts = array(
    'http' => array(
     'Content-Type: text/html; charset=utf-8', 
     'method' => "POST", 
     'header' => "Accept-language: en\r\n" . 
     "Cookie: foo=bar\r\n" . 
     'Content-length: '. strlen($data) . "\r\n", 
     'content' => $data 
    ) 
); 

$context = stream_context_create($opts); 

$fp = fopen('https://secure.ogone.com/ncol/test/orderstandard.asp', 'r', false, $context); 
fpassthru($fp); 
fclose($fp); 
+0

有沒有辦法讓這個請求強制瀏覽器顯示已發佈的頁面? –

+0

什麼瀏覽器?不fpassthru()將POST請求的內容轉儲到標準輸出? – paulgrav

1

指定content選項,並且您的代碼應該可以工作。沒有必要指定Content-length,PHP會算一下:

$opts = array(
    "http" => array(
     "method" => "POST", 
     "header" => 
      "Content-type: application/x-www-form-urlencoded\r\n" . 
      "Cookie: foo=bar", 
     "content" => http_build_query(array(
      "foo" => "bar", 
      "bla" => "baz" 
     )) 
    ) 
); 

注:

  • 在上面的例子中,服務器接收即使它沒有明確規定Content-length: 15頭。
  • POST數據的內容類型通常爲application/x-www-form-urlencoded
+0

根據RFC http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html內容長度字段「只要在傳輸之前可以確定消息的長度就應該發送」。所以,如果你可以計算出來,然後發送它。 – paulgrav

+0

是的。 PHP會通過查看內容來爲你計算它。 –