Reputation: 177
I am trying to get a server side POST to work in PHP. I am trying to send transaction data to a payment gateway but I keep getting the following error:
Message:
fopen(https://secure.ogone.com/ncol/test/orderstandard.asp)
: failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required
Code:
$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);
Tried a few solutions found online - mostly shots in the dark so no luck so far!
Upvotes: 2
Views: 3856
Reputation: 272006
Specify the content
option and your code should work. There is no need to specify Content-length
, PHP will calculate it for you:
$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"
))
)
);
Notes:
Content-length: 15
header even though it is not explicitly specified.application/x-www-form-urlencoded
.Upvotes: 1
Reputation: 624
Just add content length. Once you actually start sending content you’ll need to calculate its length.
$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);
Upvotes: 3