Меню

Header ошибка cannot modify header information headers already sent by

No output before sending headers!

Functions that send/modify HTTP headers must be invoked before any output is made.
summary ⇊
Otherwise the call fails:

Warning: Cannot modify header information — headers already sent (output started at script:line)

Some functions modifying the HTTP header are:

  • header / header_remove
  • session_start / session_regenerate_id
  • setcookie / setrawcookie

Output can be:

  • Unintentional:

    • Whitespace before <?php or after ?>
    • The UTF-8 Byte Order Mark specifically
    • Previous error messages or notices
  • Intentional:

    • print, echo and other functions producing output
    • Raw <html> sections prior <?php code.

Why does it happen?

To understand why headers must be sent before output it’s necessary
to look at a typical HTTP
response. PHP scripts mainly generate HTML content, but also pass a
set of HTTP/CGI headers to the webserver:

HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8

<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>

The page/output always follows the headers. PHP has to pass the
headers to the webserver first. It can only do that once.
After the double linebreak it can nevermore amend them.

When PHP receives the first output (print, echo, <html>) it will
flush all collected headers. Afterward it can send all the output
it wants. But sending further HTTP headers is impossible then.

How can you find out where the premature output occurred?

The header() warning contains all relevant information to
locate the problem cause:

Warning: Cannot modify header information — headers already sent by
(output started at /www/usr2345/htdocs/auth.php:52) in
/www/usr2345/htdocs/index.php on line 100

Here «line 100» refers to the script where the header() invocation failed.

The «output started at» note within the parenthesis is more significant.
It denominates the source of previous output. In this example, it’s auth.php
and line 52. That’s where you had to look for premature output.

Typical causes:

  1. Print, echo

    Intentional output from print and echo statements will terminate the opportunity to send HTTP headers. The application flow must be restructured to avoid that. Use functions
    and templating schemes. Ensure header() calls occur before messages
    are written out.

    Functions that produce output include

    • print, echo, printf, vprintf
    • trigger_error, ob_flush, ob_end_flush, var_dump, print_r
    • readfile, passthru, flush, imagepng, imagejpeg

    among others and user-defined functions.

  2. Raw HTML areas

    Unparsed HTML sections in a .php file are direct output as well.
    Script conditions that will trigger a header() call must be noted
    before any raw <html> blocks.

    <!DOCTYPE html>
    <?php
        // Too late for headers already.
    

    Use a templating scheme to separate processing from output logic.

    • Place form processing code atop scripts.
    • Use temporary string variables to defer messages.
    • The actual output logic and intermixed HTML output should follow last.
  3. Whitespace before <?php for «script.php line 1» warnings

    If the warning refers to output inline 1, then it’s mostly
    leading whitespace, text or HTML before the opening <?php token.

     <?php
    # There's a SINGLE space/newline before <? - Which already seals it.
    

    Similarly it can occur for appended scripts or script sections:

    ?>
    
    <?php
    

    PHP actually eats up a single linebreak after close tags. But it won’t
    compensate multiple newlines or tabs or spaces shifted into such gaps.

  4. UTF-8 BOM

    Linebreaks and spaces alone can be a problem. But there are also «invisible»
    character sequences that can cause this. Most famously the
    UTF-8 BOM (Byte-Order-Mark)
    which isn’t displayed by most text editors. It’s the byte sequence EF BB BF, which is optional and redundant for UTF-8 encoded documents. PHP however has to treat it as raw output. It may show up as the characters  in the output (if the client interprets the document as Latin-1) or similar «garbage».

    In particular graphical editors and Java-based IDEs are oblivious to its
    presence. They don’t visualize it (obliged by the Unicode standard).
    Most programmer and console editors however do:

    joes editor showing UTF-8 BOM placeholder, and MC editor a dot

    There it’s easy to recognize the problem early on. Other editors may identify
    its presence in a file/settings menu (Notepad++ on Windows can identify and
    remedy the problem),
    Another option to inspect the BOMs presence is resorting to an hexeditor.
    On *nix systems hexdump is usually available,
    if not a graphical variant which simplifies auditing these and other issues:

    beav hexeditor showing utf-8 bom

    An easy fix is to set the text editor to save files as «UTF-8 (no BOM)»
    or similar to such nomenclature. Often newcomers otherwise resort to creating new files and just copy&pasting the previous code back in.

    Correction utilities

    There are also automated tools to examine and rewrite text files
    (sed/awk or recode).
    For PHP specifically there’s the phptags tag tidier.
    It rewrites close and open tags into long and short forms, but also easily
    fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:

    phptags  --whitespace  *.php
    

    It’s safe to use on a whole include or project directory.

  5. Whitespace after ?>

    If the error source is mentioned as behind the
    closing ?>
    then this is where some whitespace or the raw text got written out.
    The PHP end marker does not terminate script execution at this point. Any text/space characters after it will be written out as page content
    still.

    It’s commonly advised, in particular to newcomers, that trailing ?> PHP
    close tags should be omitted. This eschews a small portion of these cases.
    (Quite commonly include()d scripts are the culprit.)

  6. Error source mentioned as «Unknown on line 0»

    It’s typically a PHP extension or php.ini setting if no error source
    is concretized.

    • It’s occasionally the gzip stream encoding setting
      or the ob_gzhandler.
    • But it could also be any doubly loaded extension= module
      generating an implicit PHP startup/warning message.
  7. Preceding error messages

    If another PHP statement or expression causes a warning message or
    notice being printed out, that also counts as premature output.

    In this case you need to eschew the error,
    delay the statement execution, or suppress the message with e.g.
    isset() or @()
    when either doesn’t obstruct debugging later on.

No error message

If you have error_reporting or display_errors disabled per php.ini,
then no warning will show up. But ignoring errors won’t make the problem go
away. Headers still can’t be sent after premature output.

So when header("Location: ...") redirects silently fail it’s very
advisable to probe for warnings. Reenable them with two simple commands
atop the invocation script:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Or set_error_handler("var_dump"); if all else fails.

Speaking of redirect headers, you should often use an idiom like
this for final code paths:

exit(header("Location: /finished.html"));

Preferably even a utility function, which prints a user message
in case of header() failures.

Output buffering as a workaround

PHPs output buffering
is a workaround to alleviate this issue. It often works reliably, but shouldn’t
substitute for proper application structuring and separating output from control
logic. Its actual purpose is minimizing chunked transfers to the webserver.

  1. The output_buffering=
    setting nevertheless can help.
    Configure it in the php.ini
    or via .htaccess
    or even .user.ini on
    modern FPM/FastCGI setups.
    Enabling it will allow PHP to buffer output instead of passing it to the webserver instantly. PHP thus can aggregate HTTP headers.

  2. It can likewise be engaged with a call to ob_start();
    atop the invocation script. Which however is less reliable for multiple reasons:

    • Even if <?php ob_start(); ?> starts the first script, whitespace or a
      BOM might get shuffled before, rendering it ineffective.

    • It can conceal whitespace for HTML output. But as soon as the application logic attempts to send binary content (a generated image for example),
      the buffered extraneous output becomes a problem. (Necessitating ob_clean()
      as a further workaround.)

    • The buffer is limited in size, and can easily overrun when left to defaults.
      And that’s not a rare occurrence either, difficult to track down
      when it happens.

Both approaches therefore may become unreliable — in particular when switching between
development setups and/or production servers. This is why output buffering is
widely considered just a crutch / strictly a workaround.

See also the basic usage example
in the manual, and for more pros and cons:

  • What is output buffering?
  • Why use output buffering in PHP?
  • Is using output buffering considered a bad practice?
  • Use case for output buffering as the correct solution to «headers already sent»

But it worked on the other server!?

If you didn’t get the headers warning before, then the output buffering
php.ini setting
has changed. It’s likely unconfigured on the current/new server.

Checking with headers_sent()

You can always use headers_sent() to probe if
it’s still possible to… send headers. Which is useful to conditionally print
info or apply other fallback logic.

if (headers_sent()) {
    die("Redirect failed. Please click on this link: <a href=...>");
}
else{
    exit(header("Location: /user.php"));
}

Useful fallback workarounds are:

  • HTML <meta> tag

    If your application is structurally hard to fix, then an easy (but
    somewhat unprofessional) way to allow redirects is injecting a HTML
    <meta> tag. A redirect can be achieved with:

     <meta http-equiv="Location" content="http://example.com/">
    

    Or with a short delay:

     <meta http-equiv="Refresh" content="2; url=../target.html">
    

    This leads to non-valid HTML when utilized past the <head> section.
    Most browsers still accept it.

  • JavaScript redirect

    As alternative a JavaScript redirect
    can be used for page redirects:

     <script> location.replace("target.html"); </script>
    

    While this is often more HTML compliant than the <meta> workaround,
    it incurs a reliance on JavaScript-capable clients.

Both approaches however make acceptable fallbacks when genuine HTTP header()
calls fail. Ideally you’d always combine this with a user-friendly message and
clickable link as last resort. (Which for instance is what the http_redirect()
PECL extension does.)

Why setcookie() and session_start() are also affected

Both setcookie() and session_start() need to send a Set-Cookie: HTTP header.
The same conditions therefore apply, and similar error messages will be generated
for premature output situations.

(Of course, they’re furthermore affected by disabled cookies in the browser
or even proxy issues. The session functionality obviously also depends on free
disk space and other php.ini settings, etc.)

Further links

  • Google provides a lengthy list of similar discussions.
  • And of course many specific cases have been covered on Stack Overflow as well.
  • The WordPress FAQ explains How do I solve the Headers already sent warning problem? in a generic manner.
  • Adobe Community: PHP development: why redirects don’t work (headers already sent)
  • Nucleus FAQ: What does «page headers already sent» mean?
  • One of the more thorough explanations is HTTP Headers and the PHP header() Function — A tutorial by NicholasSolutions (Internet Archive link).
    It covers HTTP in detail and gives a few guidelines for rewriting scripts.

Ошибка «Невозможно изменить информацию заголовка» означает, что вы правили файлы (скорее всего, wp-config.php) вручную. И правили некорректно. Необходимо сохранять файлы в кодировке UTF-8 без метки BOM (byte order mark).

Имя файла, приводящего к ошибке, и номер строки указаны в «output started at». Например:

Warning: Cannot modify header information — headers already sent by (output started at /home/user/site.ru/public_html/wp-config.php:1) in /home/user/site.ru/public_html/wp-includes/pluggable.php on line 934

означает, что проблему вызывает 1-я строка файла wp-config.php.

  1. Убедитесь, что перед первой строкой <?php и после последней ?> нет пустых строк.
  2. Избегайте править файлы в Блокноте. Используйте «программистские» редакторы вроде PSpad, Notepad++ и им подобные, в которых метка BOM отключается. В Notepad++ для этого нужно выбрать в меню «Кодировки» пункт «Преобразовать в UTF-8 без BOM».

Также к предупреждению Cannot modify header information приводит вывод любых других сообщений об ошибках, предупреждений и нотаций php, предшествующих выводу заголовков.

« Вернуться к ЧАВО

Сегодня каждый пользователь может сделать свой сайт на любом движке, в т.ч. бесплатном – Joomla, WordPress и других. Освоить азы программирования по имеющейся в сети информации тоже не составит труда. Но иногда даже малейшая ошибка в коде, допущенная при разработке сайта, может привести к его неработоспособности. И сегодня мы рассмотрим проблему Cannot modify header information — headers already sent by. И как исправить её самостоятельно, чтобы все работало без сбоев, а также разберём почему она появляется.

  • Что означает выражение Cannot modify?
  • Почему выходит ошибка и как её исправить в Вордпресс?
  • Замена неисправных файлов
  • Заключение

Картинка Cannot modify

Что означает выражение Cannot modify?

На русский язык полный текст сообщения переводится как “Нет возможности изменить заголовки – они уже были отправлены”. У этого сообщения могут еще быть такие варианты.

Как еще может выглядеть сообщение о возникшей проблеме

Другие вариации ошибки

Почему выходит такая ошибка? Чтобы понять это, необходимо узнать, как браузер отвечает на запросы пользователя. Когда мы открываем страницу, нам в первую очередь присылаются заголовки, в которых содержится следующая информация:

  • данные о сервере;
  • кодировка;
  • куки;
  • язык сайта;
  • сессия;
  • другая служебная информация.

Ошибку Cannot modify header information — headers already sent by вызывают такие PHP-команды, как setcookie, header и другие, влияющие на работу сессий или куки.

Почему выходит ошибка и как её исправить в Вордпресс?

Как мы рассмотрели выше, в первую очередь перед загрузкой страницы нам посылаются заголовки с важной информацией, а потом уже приходят запрошенные данные. По неопытности или невнимательности программисты допускают ошибку в исходном коде. Они пытаются вначале определить другие функции (чаще всего, используя, при этом команду echo), а после этого уже занимаются установкой куки или отправкой заголовков. Чаще всего из-за этого и выскакивает ошибка на WordPress.

Рассмотрим на примерах, как выглядит рассматриваемая нами проблема.

Размещение информации перед заголовками

Сначала изучим один тип ошибки, когда программист действует по неопытности либо невнимательности. Здесь показан некорректный вариант.

Код php

А сейчас – верное написание кода.

Код html

Посмотрим внимательно на картинки и найдем место, куда закралась ошибка. Как видно в неправильном варианте, перед заголовком header идет строка echo. Вот это и есть причина проблемы – никакую информацию нельзя выводить раньше заголовков. Сначала идут данные строки header и только потом – все остальное.

Появление лишнего пробела

Причиной появления ошибки Cannot modify header information может быть и лишний пробел, который незаметен при первом взгляде. Если он присутствует в коде, то, естественно, и будет загружаться раньше, чем заголовки. В результате пользователь увидит на экране сообщение об ошибке. Пустой пробел может появиться самостоятельно, если документ открывался в стандартном блокноте Windows. Этот редактор может, не уведомляя нас, добавить служебный символ Byte Order Mark, который выставляет лишний пробел перед заголовком. Чтобы проверить, в этом ли дело, документ необходимо открыть в любом другом редакторе и проверить. Возможно, в файле будет такая ситуация, как на картинке ниже.

Неверный код html

Как видим, первая строка начинается не с <?PHP, а с пробела перед данной комбинацией. Его необходимо убрать и проблема будет устранена.

Использование команды include

Многие программисты допускают ошибку при использовании команды include. Она применяется для объединения всех файлов и создания одного итогового. И, если попытаться вначале подключить шапку сайта (меню, слайдер и т. п.). А после этого оформить заголовки, то, естественно, появится сообщение об ошибке Cannot modify…

Пример ошибки в коде php

Чтобы решить проблему, необходимо функцию header (setcookie либо session_start) в скрипте разместить первой.

Обычно в сообщении об ошибке содержится информация о том, где её искать.

Указано место, где находится проблемный файл

После output started — путь к файлу с ошибкой

После слов output started следуют сведения о том, в какой строке скрипта появилась ошибка. Необходимо пройти по этому пути и, увидев проблему, решить её – убрать лишний пробел либо поставить функцию header в самом начале.

Замена неисправных файлов

Если ошибка закралась в установленные на WordPress плагины либо темы, то их можно переустановить. Но проблема может быть также в файлах ядра. В этом случае необходимо взять файл из чистой версии движка и инсталлировать его на место проблемного. Остальные (корректные) настройки сайта на WordPress останутся нетронутыми.

Заключение

Мы узнали, что означает сообщение об ошибке с текстом Cannot modify header information — headers already sent by. А также определили пути поиска проблемы и способы её решения – удаление лишнего пробела, установка функции header в самом верху скрипта или замена неисправных файлов.

Are you bogged down by the number of times you see the PHP warning “Cannot modify header information – headers already sent…”? It is not only difficult to resolve these errors but also troublesome and frustrating to debug. Take a look at the primary causes of these errors and how you can fix them quickly.

As we know, a web page is made up of two parts – the page header and the body. When a web developer incorrectly creates or modifies a page header, he may see one of the common PHP errors. The error states “Warning: Cannot modify header information – headers already sent by …” with details of the file and line of code with the error. If the developer is unaware of the cause of this error, he may spend hours to get the issue resolved. Understanding why the error occurs will help you find the solution.

Web Page Headers

When you work on PHP for creating websites, PHP would handle the work of generating web pages for you. The header contains page information and is generally generated automatically without requiring developer intervention. The header information is mostly not seen by the user.

Developers may want to modify parts of the page header. Any incorrect configuration may lead to the “Headers already sent” errors. This error may or may not be the first error message on the page. If it is not the first error, then it may have been caused due to previous errors. Fix the errors before this one and this error message would most likely be resolved.

If the error is the first error on the page then it is likely that the cause is due to some error created by the developer, in the PHP code. Here at Templatetoaster website maker, Let us look at each of the causes and the resolution for each.

Causes and Fixes for Errors in Webpage Headers

  • Page body content sent before the header

The header must, as a rule, be sent first in the response from a web server. It is divided from the body by a single blank line. If some section of the body of the web page is sent already before the request to the header, then this error may occur.

Note that the functions that create or modify the headers must be invoked before any other output is shown. Some of the functions used for modifying the HTTP header are:

  1. header
  2. header_remove
  3. session_start
  4. session_regenerate_id
  5. setcookie
  6. setrawcookie

As a first step, find the header statement that is causing the error. The actual error must be at this line or before this line. Next, try to look for statements that could send output before the header statement. If these are present, you need to change the code and move the header statement before such statements.

  • Unparsed HTML before the Header

If there are unparsed HTML sections in a PHP file then these are considered as direct output to the browser. Scripts that trigger a header () call must be called before any raw <html> blocks. You also cannot have any HTML tags present before the header function.

Incorrect usage examples:

  1. <!DOCTYPE html>
    <?php
  2. <?php <html> header('Location: http://www.google.com'); ?>

To fix this error you should separate processing code from output generation code. Place the form processing code right at the beginning of the PHP script.

  • Extra spaces or lines before <?php or after a closing?> php tag

This error also occurs due to whitespace at the beginning or at the end of a PHP file. Extra whitespace may be added by a bad unpacking program or a non-compliant editor like the Notepad, WordPad or TextEdit.

The fix is to remove that whitespace from the file. It says “output started at … “followed by a filename and a line number. That is the file (and line) that you need to edit. Ignore the second file name – that is only a file that included the file that has the whitespace. The first file is the one you have to edit, not the second one.

  • Incorrect PHP Encoding Format

In the last case, we consider the scenario when your code is correct with no white space, HTML tags, and incorrect function calls. However, the PHP code still gives the same error.

This situation is more likely due to how the PHP file was saved. With a text editor like Notepad, you can save PHP file in different encodings like ANSI, Unicode, Unicode big endian, or UTF-8 encoding. If you choose an incorrect encoding format then the PHP script can trigger this error. The best encoding format to save PHP files is the ANSI encoding.

This encoding will not add any hidden whitespaces or characters to the file. Any of the other encodings can actually add extra characters to the PHP file. This can lead to the “headers already sent” error.

Output Buffering as a Workaround

As we have seen above, it is critical to have your code structured properly and ensure that the output is separated from the code. If this cannot be achieved then as a workaround you can try using PHPs Output Buffering.

By default the output buffering is off, the HTML is sent to the browser in pieces as PHP processes the script. If the Output Buffering is on, the HTML is stored in a variable. It is then sent to the browser as one whole at the end of the script.

You can use any of the two methods below to enable output buffering.

  1. Use the Output Buffering setting to enable output buffering. You can configure it in the php.ini file, in the .htaccess file or the .user.ini files.
  2. Use a call to the function ob_start() at the start of the invocation script. This is less reliable for following reasons:
  • A whitespace or a BOM might get added before the function making it ineffective.
  • When attempting to send binary content like a generated image, the buffered unnecessary output causes a problem. This may need an ob_clean() as a further workaround.
  • The buffer which is limited in size can be easily overrun if set to default values.

How TemplateToaster helps?

If you are a newbie or a beginner in developing websites, we recommend that you try using TemplateToaster. This WordPress website Builder lets you create websites for multiple Content Management Systems like WordPress, Joomla, Drupal etc. with the flexibility to choose from a range of templates. You would not need to get into the details of the PHP, CSS, and HTML coding which would prevent getting into errors such as the “headers already sent” error.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Haven and hearth amber client ошибка
  • Have you got the aunt где ошибка