Shaun Hogg
Shaun Hogg

Reputation: 177

PHP server side post

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

Answers (2)

Salman Arshad
Salman Arshad

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:

  • In the above example, the server receives Content-length: 15 header even though it is not explicitly specified.
  • Content-type for POST data is usually application/x-www-form-urlencoded.

Upvotes: 1

paulgrav
paulgrav

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

Related Questions