PHP server side post

北城以北 提交于 2019-12-02 02:29:02

问题


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!


回答1:


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);



回答2:


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.


来源:https://stackoverflow.com/questions/13971003/php-server-side-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!