As per RFC2616 10.4.12:
10.4.12 411 Length Required
The server refuses to accept the request without a defined Content-
Length. The client MAY repeat the request if it adds a valid
Content-Length header field containing the length of the message-body
in the request message.
You need to add the Content-Length
header to your POST
request. That's the size in bytes (octets) of your POST request body. To obtain the length you could use strlen
on the POST body. As your code example does not show any POST body, it's hard to give a concrete example. The post body is passed with the ['http']['content']
entry in the stream context.
Probably it's already enough if you set the content entry (see HTTP context optionsDocs).
Edit: The following example code might solve your issue. It demonstrates how to send some XML to a server via a POST request using file_get_contents
and setting headers including the Content-Length
header.
$url = 'https://api.example.com/action';
$requestXML = '<xml><!-- ... the xml you want to post to the server... --></xml>';
$requestHeaders = array(
'Content-type: application/x-www-form-urlencoded',
'Accept: application/xml',
sprintf('Content-Length: %d', strlen($requestXML));
);
$context = stream_context_create(
array(
'http' => array(
'method' => 'POST',
'header' => implode("\r\n", $requestHeaders),
'content' => $requestXML,
)
)
);
$responseXML = file_get_contents($url, false, $context);
if (FALSE === $responseXML)
{
throw new RuntimeException('HTTP request failed.');
}
If you need better error control, see the ignore_errors HTTP context optionDocs and $http_response_headerDocs. Detailed handling of HTTP response headers is available in a blog post of mine: HEAD first with PHP Streams.