内容长度和其他 HTTP 标头?

2022-01-17 00:00:00 http-headers php

如果我在生成普通 HTML 页面时设置此标头是否会给我带来任何好处?

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

我看到一些框架会设置这个头属性,我想知道为什么......(以及其他标题,例如 Content-Type: text/html)

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:他们这样做:

ob_start();

... stuff here...

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

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

echo $content;

推荐答案

我认为这只是因为 HTTP 规范要求在所有可能的情况下都这样做.

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

应用程序应该使用这个字段来指示消息体的传输长度,除非这被第 4.4 节中的规则禁止.

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.

您还可以查看 在 Pauls Answer 上Deaomon的问题.

我想这也会回答你的问题.

I think this will answer yours too.

如果您希望某人下载带有另一个标题的文件,您还应该使用 Content-Length:例如

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);
?>

相关文章