According to the HTTP specification, you do not need to specify a Content-Length header. From RFC 2616 14.13 :
Applications SHOULD use this field to indicate the length of the transmission of the message body, unless prohibited by the rules in section 4.4.
However, this is a fairly standard requirement for most servers, and they usually send an error response if the Content-Length header is missing or incorrectly specified. For all purposes and purposes SHOULD in this case be equated to MUST.
The problem is that (especially with the keep-alive connection) the server does not know when your request message really ends without the Content-Length header. Another option, if you pass the body of the request object, send the Transfer-Encoding: chunked header and manually send one piece of the object body at a time.
So, if you want to send an entity body with your message, but don’t want to send a Content-Length header, the only real option is to send a tagged HTTP message. This is mainly required if you want to pass this object and do not know its length ahead of time.
How to encode the body of an HTTP object for streaming ...
Transfer-Encoding: chunked means that you encode the body of the HTTP message entity in accordance with the restrictions set forth in RFC2616 Sec3.6.1 . This encoding format can be applied to both requests and responses (duh, they are both HTTP messages). This format is extremely useful because it allows you to immediately start sending an HTTP message before you know the size of the object’s body, or even what the object will be. In fact, this is exactly what PHP makes transparent to you when you echo manufacturer without sending a length header, such as header('Content-Length: 42') .
I will not go into the details of encoding with encoding - this is what the HTTP specification is for, but if you want to pass the body of the request object, you need to do something like this:
<?php $sock = fsockopen($host,80,$errno, $error); $readStream = fopen('/some/file/path.txt', 'r+'); fwrite($sock, "POST /somePath HTTP/1.1\r\n" . "Host: www.somehost.com\r\n" . "Transfer-Encoding: chunked\r\n\r\n"); while (!feof($readStream)) { $chunkData = fread($readStream, $chunkSize); $chunkLength = strlen($chunkData); $chunkData = dechex($chunkLength) . "\r\n$chunkData\r\n"; fwrite($sock, $chunkData); } fwrite($sock, "0\r\n\r\n");