Content-length and other HTTP headers?

Solution 1:

I think its only because of the HTTP Spec says to do this in every case possible.

Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.

You can also look at Pauls Answer on the Question of Deaomon.

I think this will answer yours too.

Also you should use Content-Length if you want someone download a file with another header: e.g.

<?php
$file = "original.pdf"
$size = filesize($file);
header('Content-type: application/pdf');
header("Content-length: $size");
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile($file);
?>

Solution 2:

Does it give me any advantage if I set this header when generating normal html pages?

Does browser load the site faster or smoother?

For dynamically generated pages, usually not. Content-Length lets the client know how large the file is. However, if Content-Length isn't specified, the transfer is sent in chunks (with a special chunk that signifies the end of the file). The former method can result in faster transmission as the overhead of splitting into chunks is eliminated. However, this is usually best reserved for static files as the resources required to buffer the entire contents in order to determine the length may outweigh any advantages gained by setting Content-Length.

Solution 3:

The main motivation behind it is re-using an existing TCP connection in HTTP 1.1. Content-Length can demarcate where the response ends for the recipient. As for the other headers, like Content-Type which specifies the MIME-type, they are for the recipient so that she would know what to do with the result depending on the type of the content For example, in Firefox you can specify what action to perform with different MIME-types. If you can pop-up the browser's save dialog or open a PDF in viewer with Content-Type of application/pdf

Solution 4:

Where content-type: text/html is concerned, it's mainly to tell the client what to expect and usually how to handle the file. In the case of bots, it can be useful for SEO purposes as it tells the bot what type of file it's looking at which can change how it's parsed/ranked.

In the case of content-length, it's just to let the client know how large a file to expect and thus where the response ends.