header content length php

Правильная выдача заголовка Content-Length

Однажды, скачивая один из своих сайтов с помощью WGet, с удивлением обнаружил, что после каждой страницы программа останавливается и ждет несколько секунд. Да пользователи иногда тоже жаловались на то, что загрузка сайта очень долго не заканчивается. Стал разбираться, в чем дело, и вот что удалось выяснить.

Как известно, в HTTP-протоколе есть три способа сообщить клиенту о том, что передача завершена. Первый, самый старый, — разорвать соединение после того, как весь контент передан. Он же самый медленный, так как при этом не работает механизм Keep-Alive, и для следующего запроса клиент должен установить новое соединение. Второй — это передача в заголовке Content-Length длины (в байтах) передаваемого контента. И наконец, третий — передача контента блоками, перед каждым из которых передается его длина в шестнадцатеричном виде, а завершение передачи обозначается передачей блока с нулевой длиной (так наказываемый chunked transfer, возможно, о нем я напишу со временем отдельную запись).

По каким-то причинам я считал, что в случае использования PHP используется chunked transfer, причем длину chunks определяет и выдает либо сам Apache, либо модуль PHP. Увы, это оказалось не так, и на моем сайте использовался самый медленный первый способ — закрытие соединения (причем не сразу, а после какого-то тайматуа, что и вызывало задержки).

Возник вопрос, как выводить Content-Length. На первый взгляд, все просто: собрать весь выводимый HTML-код в строку-буфер, посчитать ее длину и выдать. Но во-первых, в некоторых скриптах выдача делалась сразу, а не через буфер, а во-вторых, если включено сжатие GZip, реальная длина отдаваемого контента меньше переданной в Content-Length, и клиент ждет оставшейся части до тех пор, пока не истечет таймаут соединения. (Особенно плохо к этому относятся поисковики, от такого сайт может даже выпасть из выдачи.)

Тем не менее, решение все же есть. Нужно использовать встроенный механизм буферизации вывода в PHP, в частности, функцию ob_get_length, позволюящую узнать реальную длину этого буфера. Выглядит это примерно так:

Источник

php and Content-Length header connection stall

I have a php website. Since I’m using template engine and I always do the html in «one-shot» I have the size of the html document upfront. So I decided to set Content-Length header for better performance. If I don’t set it the document is transferred using chunked encoding.

The php code for html output looks like this:

so elinks on Centos 5 was the only http client that I found which has problems accessing the site. However I don’t know how to get debug information out of it.

All tests are done on the same web server, the same php version, the same web page and with the same content. What I can think of is UTF-8 text file identifier (the few bytes in front of a text file that some browsers place)

Here is a dump of headers with wget:

update:

I was able to reproduce the problem, but only on production server. One difference I notice between the working and non-working elinks is that non-working sends this header: Accept-Encoding: gzip

Of course if it’s gzipped the size will be different. zlib.output_compression is On on php.ini. I guess that could be the problem. Also output buffering is 4096. That’s strange because most browsers use compression when available. I’ll try again in a web browser.

Yes browser (chrome) also asks for compression and gzip exists in response headers:

view source shows exactly 15916 bytes. Chrome has an option to show raw headers as well as parsed. What could be happening is that Chrome actually decompresses data before counting. Sounds strange but it’s the only explanation why GUI web browsers work and some lower level clients don’t

Источник

What’s the «Content-Length» field in HTTP header?

header content length php. Смотреть фото header content length php. Смотреть картинку header content length php. Картинка про header content length php. Фото header content length php

header content length php. Смотреть фото header content length php. Смотреть картинку header content length php. Картинка про header content length php. Фото header content length php

9 Answers 9

It’s the number of bytes of data in the body of the request or response. The body is the part that comes after the blank line below the headers.

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.

It doesn’t matter what the content-type is.

The Content-Length header is a number denoting an the exact byte length of the HTTP body. The HTTP body starts immediately after the first empty line that is found after the start-line and headers.

Generally the Content-Length header is used for HTTP 1.1 so that the receiving party knows when the current response * has finished, so the connection can be reused for another request.

Alternatively, Content-Length header can be omitted and a chunked Transfer-Encoding header can be used.

If both Content-Length and Transfer-Encoding headers are missing, then at the end of the response the connection must be closed.

The following resource is a guide that I found very useful when learning about HTTP:

header content length php. Смотреть фото header content length php. Смотреть картинку header content length php. Картинка про header content length php. Фото header content length php

One octet is 8 bits. Content-length is the number of octets that the message body represents.

header content length php. Смотреть фото header content length php. Смотреть картинку header content length php. Картинка про header content length php. Фото header content length php

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.

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.

Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given.

Note that the meaning of this field is significantly different from the corresponding definition in MIME, where it is an optional field used within the «message/external-body» content-type. In HTTP, it SHOULD be sent whenever the message’s length can be determined prior to being transferred, unless this is prohibited by the rules in section 4.4.

Источник

How to forcing set header content length?

I have a big PHP file, It takes a long time to execute. so I want to set Content-Length = 26. for don’t wait until the end. But the problem is The server always set ‘Content-Length’ as actually Length. How can I forcing Content-Length?

I try on Local server the output: Received and Processing.

but in my website server, the output is: Received and Processing. end!

how can I solve the problem.

2 Answers 2

The HTTP Content-Length header is not a timeout. It tells the receiver of an HTTP message how many bytes the body of the message contains so that the receiver knows when to stop reading more bytes from the connection. If the Content-Length header contains a wrong value, things will break. You should never have to set that header manually.

To limit execution time of a PHP script, the function set_time_limit and the global config variable max_execution_time seem to be your options.

If I have understood what you are saying in your question and subsequent comments, you want the server to acknowledge the action sooner and not wait for the processing to complete.

Tinkering with http headers is not the right way to do this. Assuming that you are not interested in any new information which might arise during processing, then there are various ways to achieve this, but you need to dissociate execution of the processing from the navigation thread.

If you trigger a second PHP process (either using the first PHP process to make an http request or from JavaScript at the browser) and set a timeout on that operation, and begin the second script with ignore_user_abort(true) then you will have achieved that. There are other solutions.

But if the delay is due to bandwidth limits you have no choice but to wait.

Источник

header

(PHP 4, PHP 5, PHP 7, PHP 8)

header — Отправка HTTP-заголовка

Описание

Список параметров

Существует два специальных заголовка. Один из них начинается с » HTTP/ » (регистр не важен) и используется для отправки кода состояния HTTP. Например, если веб-сервер Apache сконфигурирован таким образом, чтобы запросы к несуществующим файлам обрабатывались средствами PHP-скрипта (используя директиву ErrorDocument ), вы наверняка захотите убедиться, что скрипт генерирует правильный код состояния.

( «Location: http://www.example.com/» ); /* Перенаправление браузера */

Принудительно задаёт код ответа HTTP. Следует учитывать, что это будет работать, только если строка header не является пустой.

Возвращаемые значения

Функция не возвращает значения после выполнения.

Ошибки

Примеры

Пример #1 Диалог загрузки

Если нужно предупредить пользователя о необходимости сохранить пересылаемые данные, такие как сгенерированный PDF-файл, можно воспользоваться заголовком » Content-Disposition, который подставляет рекомендуемое имя файла и заставляет браузер показать диалог загрузки.

// Будем передавать PDF
header ( ‘Content-Type: application/pdf’ );

// Он будет называться downloaded.pdf
header ( ‘Content-Disposition: attachment; filename=»downloaded.pdf»‘ );

// Исходный PDF-файл original.pdf
readfile ( ‘original.pdf’ );
?>

Пример #2 Директивы для работы с кешем

PHP-скрипты часто генерируют динамический контент, который не должен кешироваться клиентским браузером или какими-либо промежуточными обработчиками, вроде прокси-серверов. Можно принудительно отключить кеширование на многих прокси-серверах и браузерах, передав заголовки:

В некоторых случаях ваши страницы не будут кешироваться браузером, даже если вы не передавали этих заголовков. В браузерах есть определённые настройки, с помощью которых пользователь может изменять обычный ход кеширования, отключать его. Вы должны переопределять любые настройки, которые могут повлиять на кеширование скрипта, отправляя приведённые выше заголовки.

Примечания

Доступ к заголовкам и их вывод будет осуществляться только в случае, если в используемом вами SAPI есть их поддержка.

Строка заголовка состояния HTTP всегда будет отсылаться клиенту первой, вне зависимости от того был соответствующий вызов функции header() первым или нет. Это состояние можно перезаписать, вызывая header() с новой строкой состояния в любое время, когда можно отправлять HTTP-заголовки.

Смотрите также

User Contributed Notes 40 notes

I strongly recommend, that you use

header($_SERVER[«SERVER_PROTOCOL»].» 404 Not Found»);

header(«HTTP/1.1 404 Not Found»);

Most of the pages were displayed correct, but on some of them apache added weird content to it:

A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)

«0» at the bottom of the page (after the complete output of my php script)

It took me quite a while to find out about the wrong protocol in the HTTP-header.

So, either you have to use the HTML meta refresh thingy or you use the following:

( «refresh:5;url=wherever.php» );
echo ‘You\’ll be redirected in about 5 secs. If not, click here.’ ;
?>

Hth someone

When using PHP to output an image, it won’t be cached by the client so if you don’t want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.

// Test image.
$fn = ‘/test/foo.png’ ;

// Getting headers sent by the client.
$headers = apache_request_headers ();

?>

That way foo.png will be properly cached by the client and you’ll save bandwith. 🙂

If using the ‘header’ function for the downloading of files, especially if you’re passing the filename as a variable, remember to surround the filename with double quotes, otherwise you’ll have problems in Firefox as soon as there’s a space in the filename.

So instead of typing:

See the page called «Filenames_with_spaces_are_truncated_upon_download» at
http://kb.mozillazine.org/ for more information. (Sorry, the site won’t let me post such a long link. )

It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location

«An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.»

According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:

Content-Disposition: attachment;
filename*= UTF-8»%e2%82%ac%20rates

for backward compatibility, what should be sent is:

Content-Disposition: attachment;
filename=»EURO rates»;
filename*=utf-8»%e2%82%ac%20rates

As a result, we should use

= ‘中文文件名.exe’ ; // a filename in Chinese characters

header ( ‘Content-Type: application/octet-stream’ );

readfile ( ‘file_to_download.exe’ );
?>

I have tested the code in IE6-10, firefox and Chrome.

Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:

Workaround: do not send those headers.

Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.

Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache’s «BrowserMatch» directive. The following example disables compression in all versions of IE:

BrowserMatch «.*MSIE.*» gzip-only-text/html

It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

( «location: 1.html» );
header ( «location: 2.html» ); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won’t see any «headers already sent» errors because the browser follows the redirect before it can display the error.

( «location: 1.html» );
echo «send data» ;
header ( «location: 2.html» ); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren’t sent until the output buffer is flushed.

();
header ( «location: 1.html» );
echo «send data» ;
header ( «location: 2.html» ); //replaces 1.html
ob_end_flush (); //now the headers are sent
?>

$code = 301 ;
// Use when the old page has been «permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred.»

$code = 302 ; (default)
// «Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field.»

$code = 303 ;
// «This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached.»

$code = 307 ;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!

// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.

You can use HTTP’s etags and last modified dates to ensure that you’re not sending the browser data it already has cached.

Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header(‘Content-Transfer-Encoding: binary’);

Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header(‘Content-Encoding: gzip’);

/* This will give an error. Note the output
* above, which is before the header() call */
header ( ‘Location: http://www.example.com/’ );
exit;
?>

this example is pretty good BUT in time you use «exit» the parser will still work to decide what’s happening next the «exit» ‘s action should do (’cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
( ‘Location: http://www.example.com/’ );
die();

there are many situations with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!

Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.

If you use something like «header(‘text/javascript’);» to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.

The proper MIME-setting function is «header(‘Content-type: text/javascript’);».

Note that ‘session_start’ may overwrite your custom cache headers.
To remedy this you need to call:

. after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.

For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn’t show until a long time or never.

After lots of research and testing, I’d like to share my findings about my problems with Internet Explorer and file downloads.

Take a look at this code, which replicates the normal download of a Javascript:

I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the «application/force-download» Content-type is sometimes required to show the download box. Use this if you don’t want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.

Now, here’s my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE. Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!

I hope this saves someone some time!

I just want to add, becuase I see here lots of wrong formated headers.

1. All used headers have first letters uppercase, so you MUST follow this. For example:

Location, not location
Content-Type, not content-type, nor CONTENT-TYPE

2. Then there MUST be colon and space, like

good: header(«Content-Type: text/plain»);
wrong: header(«Content-Type:text/plain»);

3. Location header MUST be absolute uri with scheme, domain, port, path, etc.

4. Relative URIs are NOT allowed

It will make proxy server and http clients happier.

If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example.

PHP, by default, always returns the following header:

Which your entire header response will look like

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close

If you call the header name with no value like so.

?>

Your headers now look like this:

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close

If you haven’t used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

header(«status: 204»); (or the other call)
header(«HTTP/1.0 204 No Response»);

I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don’t quite understand it, I hope my posting here does help others with similar issues:

My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.

After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to ‘Always perform this operation with this file type’.

As I found out, the problem was in the header directive ‘Content-Disposition’, namely the ‘attachment’ directive.

If you want your browser to simulate a plain link to a file, either change ‘attachment’ to ‘inline’ or omit it alltogether and you’ll be fine.

This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.

A call to session_write_close() before the statement

( «Location: URL» );
exit();
?>

is recommended if you want to be sure the session is updated before proceeding to the redirection.

We encountered a situation where the script accessed by the redirection wasn’t loading the session correctly because the precedent script hadn’t the time to update it (we used a database handler).

(But the strange behaviour of dirname is a problem for URL ending by a directory without file name!)

The piece of code in the manual which is as follows

This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:

Here is a php script I wrote to stream a file and crypt it with a xor operation on the bytes and with a key :

The encryption works very good but the speed is decrease by 2, it is now 520KiB/s. The user is now asked for a md5 password (instead of keeping it in the code directly). There is some part in French because it’s my native language so modify it as you want.

// Stream files and encrypt the data on-the-fly

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *