Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content-length and other HTTP headers?

Tags:

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

I see that some frameworks out there will set this header property and I was wondering why... (Along with other headers, like Content-Type: text/html)

Does browser load the site faster or smoother?

ps: they do it like:

ob_start();

... stuff here...

$content = ob_get_contents();
$length = strlen($content);

header('Content-Length: '.$length);

echo $content;
like image 523
ellabeauty Avatar asked Mar 15 '12 21:03

ellabeauty


People also ask

What is HTTP header content-Length?

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

Is content-Length a header?

The Content-Length header indicates the size of the message body, in bytes, sent to the recipient.

Is content-Length required in HTTP?

The Content-Length is optional in an HTTP request. For a GET or DELETE the length must be zero. For POST, if Content-Length is specified and it does not match the length of the message-line, the message is either truncated, or padded with nulls to the specified length.


2 Answers

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);
?>
like image 55
Neysor Avatar answered Oct 05 '22 14:10

Neysor


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.

like image 26
webbiedave Avatar answered Oct 05 '22 16:10

webbiedave