Jak
Jak

Reputation: 1229

PHP POST with custom headers giving HTTP 400 Bad Request Response (Bug?)

I'm having some trouble POSTing data from a client machine to our internal site using PHP. The server accepts data via HTTPS with basic authentication. Here is the code I'm using to POST with:

$parameters = array('http' => array(
        'method' => 'POST',
        'content' => $data
        )
);
if ($optionalHeaders !== NULL) {
    $parameters['http']['header'] = $optionalHeaders;
}

$ctx = stream_context_create($parameters);
$fp = fopen($url, 'rb', false, $ctx);

With the following header:

$postHeader = "POST /index.php HTTP/1.1\r\n".
    "Host:my.host\r\n".
    "Content-Type: application/x-www-form-urlencoded\r\n".
    "User-Agent: PHP-Code\r\n".
    "Content-Length: " . strlen($postData) . "\r\n".
    "Authorization: Basic ".base64_encode($user.':'.$password)."\r\n".
    "Connection: close\r\n";

Now, I can get this to work, and it posts just fine on one of my clients with PHP version 5.2.5, but the on another client I get this error message:

fopen(magical_url): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

And Apache error log gives:

request failed: error reading the headers

The only difference I can see is that the latter client has PHP version 5.1.6. Does anyone know if this is a bug? Or am I doing something wrong somewhere... I've looked through the PHP site and found this bug listed for version 5.2.6 of PHP https://bugs.php.net/bug.php?id=45540 but this post-dates the version it works on!

Thanks, Jak

Upvotes: 2

Views: 2875

Answers (1)

cweiske
cweiske

Reputation: 31078

You should not provide all those headers. That's bound to fail.

Headers like POST, Host, Content-Length and Connection are automatically provided. Remove all your optional headers (should work then) and add them step by step.

Upvotes: 3

Related Questions