Беглец information headers. Как найти и побороть BOM — неприятная ошибка в WordPress

Understanding HTTP headers and HTTP header fields

HTTP headers provide vital information required for a HTTP transaction send via http protocol .

The general HTTP header format contains colon-separated name - value pairs in the header field. Each of the name-value pair end with a carriage return (CR) and a line feed (LF) character sequence. Empty fields at the end of each header indicate the end of the header.

The common header format followed by applications looks like:

Types of HTTP headers

There are four types of HTTP message headers. They are:

  • General Header
  • Request Header
  • Response Header
  • Entity Header

General Header

General Header fields have common applicability in request and response messages. The header fields apply only to the transmitted message and do not apply on the transferred entity.

The structure of a general header looks like:

Cache-control field specifies directives that have to be followed by every caching mechanism on a request and response system.

Connection field allows the sender to specify options required for a connection. The connection header has the following format:

Date field represents the date and time during the initiation of the message. The date format specified in HTTP look like:

Pragma field helps to include implementation specific directive applicable to any recipient on a request and response system.

Trailer field value specifies whether a set of header fields in message trailer is encoded with chunk transfer-coding.

Transfer-Encoding field indicate whether any type of transformation is applied to the message body.

Upgrade field enables clients to specify additional supported communication protocols. It also enables the server to switch protocols with the additional protocols.

Via field are mandatory fields used by proxies and gateways which indicate intermediate protocols. It also indicates request recipient between user-agent and server and response between server and client.

Warning field carries additional information on message status and message transformations which are not reflected in the message.

Warning headers are usually sent with responses.

The request header field allows clients to additionally pass request information and client information to the server.

The structure of a request header looks like:

Accept field specifies media types which are acceptable for response.

"*" is used to group media types in range

"*/*" indicate all media types

"type/*" indicate all subtypes of a type

Accept-Charset field indicates response acceptable character sets. It makes clients capable to understand special-purpose character sets to signal the server to represent the document in these character sets.

Accept-Encoding field is similar to Accept, restricts response acceptable content-coding.

Accept-Language field is similar to Accept, restricts preferred set of natural languages.

Authorization field is for user agents who wish to authenticate themselves with the server.

Expect field indicates server behaviors required by a client.

From field contains e-mail address of a user who controls the requesting user-agent.

Host field specifies the internet host and requested resource port number from user URI.

If-Match field is used to make conditional methods.

If-Modified-Since field is used to make a conditional method. If the requested variant is not modified within the specified time, the entity will not be returned from the server.

If-None-Match field allows efficient update of cache information with minimum transaction overhead.

If-Range field allows clients to receive part of the missing entity or otherwise, clients can ask to send the entire new entity.

If-Unmodified-Since field allows the server to perform requested operation if it has not been modified since the time specified in this field.

Max Forwards field provides mechanisms with TRACE and OPTIONS methods to limit the request forwarding proxies or gateways.

Proxy Authorization field allows client to identify to secure proxy.

Range field specifies the HTTP entities in HTTP messages represented as a sequence of bytes. HTTP retrieval request requests one or more sub range of entity using GET methods.

Referrer field allows clients to specify the address URI of the resource from which Request-URI is found.

TE field indicates extension transfer-coding it can accept in the response. Additionally, it indicates whether it will accept trailer fields in chunk transfer-coding.

User-Agent field contains information about the requesting user-agent.

HTTP Response Header

The response header field allows the server to pass additional information through the responses other than simple Status-Line response.

The structure of the response header looks like:

Accept-Ranges field enables servers to indicate acceptance of resource range requests.

Age field indicates sender the approximate amount of time since server responded.

ETag field provides current value of the entity tag for a request.

Location field redirects recipients to locations other than Request-URI to complete identification of a new resource.

Proxy-Authenticate field is a mandatory inclusion for proxy authentication response.

Retry-After field is used as a response when a service is unavailable to indicate the length of period for which service will remain unavailable to the client.

Server field contains information about software used by server to handle requests.

Vary field indicates request field that determine whether a cache is eligible to use the response of a request without revalidation of the response.

WWW-Authenticate field are used when a response message is unauthorized.

Entity header fields define metainformation about the entity-body or the requested resource. The entity-header format looks like:

Allow field list the set of methods supported by Request-URI identified resources.

Content-Encoding field is used as a media-type modifier.

Content-Language field describes natural language for clients of an entity.

Content-Length field indicates the size of an entity represented in decimal number.

Content-Location field provides resource location for an entity when it is accessible from a location other than Requested-URI.

Content-MD5 field provides message integrity check (MIC) using an MD5 digest on the entity body.

Content-Range field specifies where partial body of the full entity-body should be applied.

Content-Type field indicates whether the media type of the entity body is sent to the recipient or GET method is used to send requests.

Expires field provides the date/time after which the response becomes stale.

Last Modified field indicates the date and time of last modification of the variant.

The order in which field name appears in the header when received is insignificant. Conventionally general headers are placed first, followed by request or response header with entity header at the end.

Copyright Notice: Please don"t copy or translate this article without prior written permission from the сайт

HTTP Debugger is a proxy-less HTTP analyzer for developers that provides the ability to capture and analyze HTTP headers, cookies, POST params, HTTP content and CORS headers from any browser or desktop application. Awesome UI and very easy to use. Not a proxy, no network issues!

С этой ошибкой ко мне постоянно обращаются и спрашивают: "Где ошибка? ". Подобных писем за всё время я получил где-то штук 500 , не меньше. Пора с ошибкой "" уже заканчивать. В этой статье я расскажу о причинах возникновения данной ошибки, а также о том, как её решить.

Если перевести данную ошибку на русский язык, то получится примерно следующее: "Нельзя изменить заголовок, поскольку они уже отправлены ". Что это за "заголовки "? Давайте разберёмся.

Когда сервер возвращает ответ клиенту, помимо тела (например, HTML-кода страницы), идут ещё и заголовки. В них содержится код ответа сервера, cookie , кодировка и множество других служебных параметров. Может ли PHP-скрипт отправить заголовок? Конечно, может. Для этого существует функция header() .

Данная функция, например, постоянно используется при . Также данная функция регулярно используется при .

Также заголовки модифицируются при отправке cookie и при начале сессии (функция session_start() ).

А теперь о том, почему же всё-таки возникает ошибка? Сервер всегда сначала отдаёт серверу заголовки, а потом тело. Если сервер уже вернул заголовки, потом пошло тело, и тут он встречает какой-нибудь session_start() . Оказывается горе-программист забыл отправить заголовки до начала тела, и теперь хочет догнать уже ушедший поезд.

Вот код с ошибкой "":



?>

Разумеется, такой бред PHP не прощает. И надо было писать так:

session_start(); // А давайте начнём сессию
?>

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

Другой пример кода с ошибкой:

echo "Hello!"; // Что-нибудь выведем
session_start(); // А давайте начнём сессию
?>

То же самое, почему-то сначала выводится тело (либо его кусок), а потом вспомнили, что ещё и надо заголовки модифицировать.

Как будет правильно переписать данный код, подумайте сами.

Ещё пример:




exit;
?>

Когда у автора такого кода, ничего не получается, он удивляется от этой ошибки и говорит: "Очень странное совпадение, когда операция проходит успешно, всё хорошо, а когда какая-то ошибка, мне сообщают Cannot modify header information - headers already sent". Не дословно, но смысл именно в этом.

Проблема та же самая, и правильно писать так:

$error = true; // Были ли ошибки?
if ($error) echo "Произошла ошибка";
else header("Location: ".$_SERVER["HTTP_REFERER"]); // Делаем редирект обратно
exit;
?>

Есть и труднозаметные ошибки:

header("Location: ".$_SERVER["HTTP_REFERER"]); // Делаем редирект обратно
exit;
?>

Ошибка в данном коде возникает из-за пробела , который присутствует перед . Пробел - это обычный символ, и он является частью тела ответа. И когда сервер его видит, он делает вывод о том, что заголовков больше не будет и пора выводить тело.

Бывают и следующие ошибки, имеющие всё ту же природу. Допустим есть файл a.html :

require_once "a.html";
header("Location: ".$_SERVER["HTTP_REFERER"]); // Делаем редирект обратно
exit;
?>

И человек искренне удивляется, откуда ошибка, если он ничего не выводил? Поэтому смотреть надо не конкретно 1 файл, а все файлы, которые подключаются в нём. И в тех, что подключаются у подключаемых, тоже надо смотреть, чтобы не было вывода.

И последний момент, но уже более сложный. Оказывается, что иногда эта ошибка происходит и при правильном коде. Тогда всё дело в кодировке . Убедитесь, что кодировка файла "UTF-8 без BOM ", причём именно "без BOM ", а не просто "UTF-8 ". Поскольку BOM - это байты, идущие в самом начале файла, и они являются выводом.

Очень надеюсь, что данная статья поможет решить абсолютно все проблемы, связанные с ошибкой "", поскольку я постарался осветить все возникающие проблемы. А дальше надо включить голову, и подумать, а что в Вашем коде не так?

Ошибку эту исправить несложно.
Часто такое же сообщение появляется при старте сессий, в немного другой формулировке:
Warning: Cannot send session cookie - headers already sent
Warning: Cannot send session cache limiter - headers already sent

Byte Order Mark
Иногда вы проверили ВСЁ - нигде ничего нет. Смените редактор. Посмотрите свой файл в другой программе. К примеру, Windows Блокнот при использовании кодировки Unicode добавляет в начало вашего файла служебный символ Byte Order Mark , никак при этом не ставя вас в известность. Откройте скрипт в другом редакторе и удалите посторонние символы. И смените Блокнот на другой редактор.
Или сохраняйте в кодировке UTF-8 without BOM

Многочисленные вопросы на форуме заставляют меня сделать здесь важное замечание:
Эта ошибка появляется не от того, что у вас в скрипте "что то написано выше". А от того, что РНР выводит что-то в браузер. Это не обязательно код. Это может быть сообщение об ошибке . может быть пробел или хтмл тег. Да-да. Для самых талантливых: речь идет о любом символе, отправленном в браузер, а не только о тех, которые браузер отображает неискушенному пользователю. У HTML страниц есть исходный текст. И именно он является результатом работы PHP скрипта, а не красивые буковки с картиночками, как думает очень большое количество людей.

Как-то раз, зайдя на свой блог я с удивлением обнаружил непонятную ошибку, что-то вроде:

Warning: Cannot modify header information — headers already sent by (output started at /xxxxxxxx/wp-config.php:1)

Причем в админку зайти никак нельзя. Сразу же пошел проверять что не так с файлом wp-config.php. Все было на месте, пароли к БД правильные. Подумал было — снова хакнули)) Но опять же никаких признаков вандализма на FTP замечено не было. Самое странное (это меня в конце-концов окончательно запутало), что не работала только ссылка на сайт без www или наоборот (точно не помню). Начал стучать хостеру, смотреть настройки в админке домена — в общем, много чего.

А оказалось все намного проще — в начале файла конфига был некий BOM — маркер (сигнатура) для UTF-8 файлов. Именно поэтому выскакивала приведенная выше ошибка. Чтобы такого не случилось с вами в первую очередь нужно использовать редакторы кода, которые либо не ставят эту сигнатуру вообще, либо перед сохранением файла уточняют нужна ли она.

В некоторых текстовых редакторах вы можете найти в настройках флажки «Include Unicode Signature (BOM)», «Add Byte Order Mark» или подобные им. В противном случае, не имея возможности отключить ненужную опцию в той или иной программе, использовать ее не рекомендуется. На специализированных форумах можно найти список хороших текстовых редакторов, это — Notepad2, PSPad, UnicEdit, Notepad++ . О последнем вообще много пишут, достаточно мощный инструмент. У меня каким-то случайным образом на компа был в наличии альтернативный редактор — Akelpad — его для подобных задач и применяю.

Следует заметить вот еще какой момент — ошибка с BOM может быть не только в файле wp-config.php. Более того, при отключенной опции вывод предупреждений, вы вообще не увидите где закралась неполадка. В таких случаях (ну и всех других) я бы рекомендовал использовать простой скрипт для поиска файлов с BOM . За разработку следует поблагодарить Юрия Белотицкого .

Использование скрипта очень простое.

  1. нужный файлик
  2. Заливаете его на FTP сервер в корневую директорию. Если WordPress установлен не в корне сайта (а в папке blog, например), то скрипт нужно разместить в директорию, где лежит WordPress, и из нее же и запускать.
  3. Запуск очень простой — набираете в адресной строке броузера ссылку http://ваш.сайт/find_bom.php

В результате получите список файлов, которые являются неисправными. Кстати, для быстроты работы скрипт проверяет только те директории, куда пользователи, как правило, заливают файлы — корень, /wp-content/themes и /wp-content/plugins.

Вот, в принципе, и все. Как сложно пришлось решать такую простую проблему. Надеюсь, вам помог немного своим опытом, и теперь при появлении соответствующего предупреждения, вы будете знать, что делать:) Если не получается исправить тот или иной файл от BOM, можно просто залить новый из дистрибутива WordPress.

P.S. Для молодоженов подходящий сайт — организация банкетов и решение всех вопросов, связанных со свадьбой.