Cannot send session cache limiter headers already sent как исправить

Подскажите, пожалуйста. Как исправить такую ошибку?

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/u22691/domains/pokess.u-gu.ru/public_html/game/fight.php:1) in /home/u22691/domains/pokess.u-gu.ru/public_html/game/fight.php on line 2

Nicolas Chabanovsky's user avatar

задан 29 фев 2012 в 10:05

oOKomarOo's user avatar

oOKomarOooOKomarOo

4881 золотой знак11 серебряных знаков34 бронзовых знака

1

Видимо файл сохранен в кодировке utf-8 with bom, сохраняйте без bom.

ответ дан 29 фев 2012 в 11:09

tranceman's user avatar

2

headers already sent

Ну блин почти же по-русски написано link

Перед session_start() не должно быть никакого вывода на экран, даже пробела.

ответ дан 29 фев 2012 в 10:09

DemoS's user avatar

DemoSDemoS

3,93119 серебряных знаков41 бронзовый знак

2

Перед сессией ничего не должно быть напсано, а так же стоит посмотреть кодировку.
еще можно проверить файл php.ini

ответ дан 29 фев 2012 в 12:27

kira's user avatar

kirakira

1937 серебряных знаков25 бронзовых знаков

типичная ошибка следующая:

<? 
код php
?>

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

ответ дан 10 мар 2012 в 11:01

Cooleronline's user avatar

CooleronlineCooleronline

3441 серебряный знак6 бронзовых знаков

Проблема может быть не столь очевидна, если ты программируешь классами. Например ты описываешь
session_start() в главном файле с родительским классом. Там у тебя всё правильно написано: никаких выводов, никаких пробелов до начала сесии. Но при входе на сайт у тебя запускается файл потомок, то-есть почти всегда index.php. В тексте ошибки написана ссылка на ту строку, где объявлено начало сесии но проблема может быть и во всех файлах к которым ты подключаешь
родительский класс с вызовом session_start(). Поэтому во всех файлах где есть присоединение например чтото вроде этого

require_once($_SERVER['DOCUMENT_ROOT'] . '/admin/'файл с session_start() функцией'.php');
class index extends название класса

Так вот до этих 2 строчек во всех файлах ничего не должно выводится. А вот после них – вполне возможно.

Deleted's user avatar

Deleted

3611 золотой знак5 серебряных знаков13 бронзовых знаков

ответ дан 19 июн 2013 в 7:02

vano's user avatar

vanovano

192 бронзовых знака

Проблема может быть и в следующем случае.

К примеру форма на php встроена в HTML. Работает, всё нормально. далее что либо добавляете в HTML . . . и приехали, вылетает сообщение. Ни один из вариантов вверху не помогает, ни с сохранением без ВОМ, ничего . . . это происходит из – за разницы в кодировке текста, который добавляете при помощи копипаст . . . Любые попытки сохранения итогового текста в UTF-8 либо в ANSI не приведут к нормальной работе скрипта.

Выход – рабочий вариант странички с формой на php открываете в текстовом редакторе и вносите изменения вручную. Затем просто сохраняете без функции сохранить как! Всё будет работать без ошибок. Извиняюсь за слишком подробный мануал.

ответ дан 20 ноя 2020 в 8:29

Igor Savch's user avatar

1

Собсна при загрузке главной страницы сразу выскакивает данная ошибка :

Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:OpenServerdomainslocalhostphpMyAdminHunterDiscoBarindex.php:1) in C:OpenServerdomainslocalhostphpMyAdminHunterDiscoBarindex.php on line 2

Имеется только

<?php
session_start();
?>


  • Вопрос задан

    более трёх лет назад

  • 6401 просмотр

headers already sent. Что переводится, как “Заголовки уже отправлены”. Для запуска сессии, php выставляет куку на клиенте. Cookies устанавливаются с помощью отправки соответствующих заголовков. И, если заголовки были отправлены ранее, то возникает такая ошибка. Для того, чтобы решить эту “проблему”, необходимо проверить, есть ли где-то в коде (до этого места) вывод данных. Это может быть echo, или же вообще, пустая строка перед открывающимся тэгом <?php. Если ничего не обнаружили, попробуйте изменить кодировку файла на UTF-8 без BOM.

Пригласить эксперта

Текстовый редактор показывал кодировку UTF- 8 not BOM. Поменял на UTF-8, затем обратно сменил на UTF- 8 not BOM и все заработало.


  • Показать ещё
    Загружается…

20 мая 2023, в 03:03

4000 руб./за проект

20 мая 2023, в 02:13

1000 руб./за проект

20 мая 2023, в 01:15

100000 руб./за проект

Минуточку внимания

This guide will walk you through the process of resolving the common PHP error “Cannot send session cache limiter – headers already sent”. This error occurs when your PHP script attempts to start a session after the HTTP headers have already been sent to the browser, causing issues with session management. We will cover the reasons for this error and provide step-by-step solutions to fix it.

Table of Contents

  1. Understanding the Error
  2. Identifying the Causes
  3. Step-by-Step Solutions
  • Fixing Whitespace and BOM issues
  • Moving Session_Start()
  • Using Output Buffering
  1. FAQs
  2. Related Links

Understanding the Error

The “Cannot send session cache limiter – headers already sent” error typically occurs when your PHP script attempts to start a session using session_start() after the HTTP headers have already been sent to the browser. Once the headers have been sent, you can no longer modify them, which is necessary for managing sessions.

Identifying the Causes

The most common causes of this error are:

  1. Whitespace or any output before the session_start() function call.
  2. The Byte Order Mark (BOM) included in the file encoding.
  3. The session_start() function is called after the HTML, or any other output has been sent to the browser.

Step-by-Step Solutions

Fixing Whitespace and BOM issues

  1. Open your PHP script in a text editor.
  2. Ensure there is no whitespace or any other output before the opening <?php tag.
  3. Save the file with UTF-8 encoding without BOM. In most text editors, you can find this option in the “Save As” dialog box.

Moving Session_Start()

  1. Locate the session_start() function in your PHP script.
  2. Move the session_start() function to the beginning of your script, before any output (including HTML, echo statements, or print statements) is sent to the browser.
  3. Save the changes and test your script.

Using Output Buffering

  1. At the beginning of your PHP script, add the following line to enable output buffering:
<?php ob_start(); ?>
  1. At the end of your PHP script, add the following line to flush the output buffer:
<?php ob_end_flush(); ?>
  1. Save the changes and test your script.

FAQs

Q: What is the session cache limiter?

A: The session cache limiter is a configuration setting that controls the caching behavior of session data. It can be set to various values, such as “nocache”, “public”, “private”, or “private_no_expire”, depending on your desired caching behavior.

Q: Can I use output buffering in all my PHP scripts?

A: Yes, you can use output buffering in all your PHP scripts. However, it is not always necessary and can sometimes cause performance issues if not used properly.

Q: What is the Byte Order Mark (BOM)?

A: The Byte Order Mark (BOM) is a Unicode character used to indicate the byte order of a text file. It is sometimes included in the file encoding and can cause issues with PHP scripts.

Q: Can I use ini_set() to modify the session.cache_limiter setting?

A: Yes, you can use the ini_set() function to modify the session.cache_limiter setting at runtime. For example, you can use the following code to disable caching:

<?php ini_set('session.cache_limiter', 'nocache'); ?>

Q: Why is it important to start the session before sending any output to the browser?

A: Starting the session before sending any output to the browser is important because it allows PHP to modify the HTTP headers, which are necessary for managing sessions. Once the headers have been sent, you can no longer modify them, causing issues with session management.

  • PHP: session_start() – Manual
  • PHP: Output Control Functions – Manual
  • PHP: Byte Order Mark (BOM) – Stack Overflow
  • PHP: Understanding Sessions – SitePoint

Доброго времени суток, коллеги! Сегодня расскажу, как я боролся с этой ошибкой, о которой вы могли прочитать в заголовке поста. То, что вы читаете этот пост показывает, что вы тоже столкнулись с ней. А может у вас возникали и другие ошибки? Не стесняйтесь писать об этом в комментариях, я буду очень рад. Чтобы у нас было поменьше разных ошибок необходимо иметь опыт. Не правда ли? В конце статьи вы найдете, то что поможет вам его приобрести. А теперь приступим к нашей ошибке!
При написании:

<?php
	session_start();
?>

Вышла ошибка:

Warning: session_start() [function.session-start]: Cannot send session cache limiter — headers already sent (output started at X:/home/localhost/www/phpbloguser/header.html:6) in X:/home/localhost/www/phpbloguser/blocks/global.inc.php on line 110

Оказывается в php.ini нужно директиву output_buffering поставить в «On» (по умолчанию — Off), см. php.ini. И всё получиться! Чтобы заработало нужно перезагрузить Ваш сервер.

Ещё эта ошибка возникает по другим причинам:

Нужно посмотреть, может есть пробел, таб, перенос строки перед «<?».

Кроме того, стартовать сессию нужно до того, как что-либо будет выведено в окно браузера. Так как идентификатор сессии в данном случае пишется в файлы cookie. Куки, в свою очередь, всегда устанавливаются через отправку заголовков — headers.

Здесь же написано, что заголовки УЖЕ были отправлены. Поэтому нужно проверить, не выводиться ли что-нибудь в окно браузера, до того как я стартую сессию с помощью session_start()?

Еще ваш php файл должен быть сохранен в кодировке UTF 8 (без BOM), если с BOM, то вначале файла всегда выводятся три символа, вот и возникает эта ошибка.

30.06.2010//



https://site.softmaker.kz/wp-content/uploads/2010/06/ErrorMethodHeaders.jpg
300
450


softmaker

https://site.softmaker.kz/wp-content/uploads/2015/11/icon_site_shadow.png

softmaker2010-06-30 00:00:002021-06-06 14:45:37Почему в PHP выдается ошибка: Cannot send session cache limiter — headers already sent?

Have you ever had trouble with the session start of PHP? For example, when you started a session on a particular page, did you get the error: Warning: session_start(): cannot send session cache limiter – headers already sent before? Actually, the error means that some data has been already sent to the server and you are not able to send the header anymore.

If you are seeking some solutions to solve this trouble, we would like to show you some suggested methods that help other users successfully fix it. So, now, let’s start!

Warning: Session_Start(): Cannot Send Session Cache Limiter - Headers Already Sent

Here are some ways you should try one by one to find the most useful one.

  • Solution 1: Check out the code and make sure that the
    <?php
    is the first character. That means there is no space or tab before.
  • Solution 2: Put the code
    <?php session_start(); ?>
    above all other code.
  • Solution 3: Change the encoding of the document from UTF-8 to ANSI. Or you can use UTF-8 encoding without BOM (Byte Oder Mark) by ensuring that you don’t use notepad.exe to edit or save the files since it will insert UTF-8 BOM.

Conclusion

All in all, we have already shared with you the three methods to fix this common error: Warning: session_start(): cannot send session cache limiter – headers already sent. Therefore, we hope that it will be useful for you. If you have more ideas to address this trouble, don’t hesitate to let us know by leaving your comment below.

Furthermore, if you are using WordPress or Joomla and want to change the appearance of your site, let’s have a look at the collection of Free WordPress Themes as well as Joomla 4 Templates here. Thanks for your attention and have a wonderful day.

  • Author
  • Recent Posts

Lt Digital Team (Content &Amp; Marketing)

Welcome to LT Digital Team, we’re small team with 5 digital content marketers. We make daily blogs for Joomla! and WordPress CMS, support customers and everyone who has issues with these CMSs and solve any issues with blog instruction posts, trusted by over 1.5 million readers worldwide.

Lt Digital Team (Content &Amp; Marketing)

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