我想让服务器端POST在PHP工作。我试图将交易数据发送到支付网关,但我一直得到以下错误:
代码:消息:
fopen(https://secure.ogone.com/ncol/test/orderstandard.asp)
: failed to open stream: HTTP request failed!HTTP/1.1 411长度要求
$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);
尝试了一些在网上找到的解决方案-大多是在黑暗中拍摄,所以到目前为止还没有运气!
只需添加内容长度。一旦你真正开始发送内容,你需要计算它的长度。
$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);
指定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
。