Php include cannot modify header information headers already sent by

Error — Warning: Cannot modify header information — headers already sent by

Warning: Cannot modify header information — headers already sent by (output started at /home/ya3mblog/public_html/wp-login.php:59) in /home/ya3mblog/public_html/wp-includes/pluggable.php on line 866 website: ipublisharticles.com Error is at: ipublisharticles.com/wp-login.php?action=register

4 Answers 4

Add this code in wp-config.php on the first line:

ob_start(); error_reporting(0); 

Can anyone tell why this works? Couldn’t this lead to performance problems later? It works for me,too btw. I put it on top of functions.php.

I don’t think this is a great way to solve the issue, because you don’t solve the issue itself. You just «turn off» logging.

(This error) is usually because there are spaces, new lines, or other stuff before an opening tag, typically in wp-config.php.

Open the file with a plain text editor (like Notepad or BBEdit) and clear out the white space. Check that the very first characters are or a closing tag ?> with no blank lines or spaces after it. (FYI, a PHP file can run fine without the closing ?> tag.)

When saving, be sure the file encoding is not UTF-8 BOM but plain UTF-8 or any without the BOM suffix.

This could be true about some other file too, so please check the error message, as it will list the specific file name where the error occurred. Replacing the faulty file with one from your most recent backup or one from a fresh WordPress download is your best bet.

If the error message states: Warning: Cannot modify header information — headers already sent by (output started at /path/blog/wp-config.php:34) in /path/blog/wp-login.php on line 42 , then the problem is at line #34 of wp-config.php, not line #42 of wp-login.php. In this scenario, line #42 of wp-login.php is the victim. It is being affected by the excess whitespace at line #34 of wp-config.php.

If the error message states: Warning: Cannot modify header information — headers already sent by (output started at /path/wp-admin/admin-header.php:8) in /path/wp-admin/post.php on line 569 , then the problem is at line #8 of admin-header.php, not line #569 of post.php. In this scenario, line #569 of post.php is the victim. It is being affected by the excess whitespace at line #8 of admin-header.php.

Источник

Cannot modify header information — headers already sent by

значит перед этим было что то выведено. Проверьте классические проблемы — перед первым нет пробелов или пустых строк. — Ваш код не выводит с помощью echo/pring что то до установки кук — что текст сохранен без BOM. Если Вы пользуетесь блокнотом или подобным, то они могут добавлять в начало, если сохраняете в UTF-8.

Классические проблемы — перед первым нет пробелов или пустых строк. – Решил проблему, были пустые строки после ?> .

3 ответа 3

Общение WEB-сервера с клиентом в данном случае происходит по протоколу HTTP. HTTP включает в себя HTTP заголовки и тело ответа. При этом заголовки обязательно следуют перед телом ответа – того требует стандарт.

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

 Warning: Cannot modify header information - headers already sent by (output started at . 

Это может быть следствием следующих причин:

    Перед установкой заголовков был вывод тела ответа. При этом вывод может быть осуществлен как средствами шаблонизатора, так и через функции echo или print

 // вывод средствами шаблонизатора "; // вывод средствами оператора header( "Content-Type: text/html; charset=utf-8" ); 
 include( "include.inc" ); // include.inc может формировать тело ответа header( . ); 
 $filename= ""; $text= file_get_contents( $filename ); // Warning: file_get_contents(): Filename cannot be empty header( . ); 

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

Если же приходится работать с устаревшим кодом где всё вперемешку, можно воспользоваться буферизацией вывода явным образом:

   "; header("Content-Type: text/html; charset=utf-8"); ob_end_flush(); 

либо настройками php.ini принудить PHP сперва наполнять буфер данными до определенного размера, и лишь потом отдавать содержимое буфера клиенту, но в этом случае превысив размер буфера Вы увидите Выше описываемую ошибку.

Источник

Warning: Cannot modify header information — headers already sent by [duplicate]

Please save me. I know that this question has been asked many times, however, I can’t seem to find solutions that are relevant to my situation. The problem: Warning: Cannot modify header information — headers already sent by (output started at /. /Sites/st.ambulance/resources/views/login.view.php:32) in /. /Sites/st.ambulance/resources/controllers/tables_.php on line 47 This is the code block with line 32:

is_seatOccupied($volunteer['table'],$volunteer['seat_no']) != "") $table_seat_error .= "Seat (".$volunteer['seat_no'].") at table (".$volunteer['table'].") is currently occupied"; if($_SESSION['no_guests'] >= 1) < if($guest && $volunteer)< foreach($guest as $gue)< $seat_table = $gue['seat_no'].$gue['table']; for($h=0;$hif($form->is_seatOccupied($gue['table'], $gue['seat_no']) != "") $table_seat_error .= "Seat (".$gue['seat_no'].") at table (".$gue['table'].") is currently occupied"; $seat_array[] = $seat_table; > if($seat_count == 0) < if($table_seat_error == "")< for($d=0;$d<$_SESSION['no_guests'];$d++)< $_SESSION['guests'][$d]['table'] = $guest[$d]['table']; $_SESSION['guests'][$d]['seat'] = $guest[$d]['seat_no']; >$_SESSION['volunteer']['table'] = $volunteer['table']; $_SESSION['volunteer']['seat'] = $volunteer['seat_no']; $form->set_guests($_SESSION['guests']); $form->set_volunteer($_SESSION['volunteer']); header('location: /branch/menus.php'); //line 47 exit(); > else < $error = $table_seat_error; >> else < $error = "You have selected the same seat for two or more people: one person, per seat, per table. Only."; >> > else< $_SESSION['volunteer']['table'] = $volunteer['table']; $_SESSION['volunteer']['seat'] = $volunteer['seat_no']; if(!$form->is_seatOccupied($_SESSION['volunteer']['table'], $_SESSION['volunteer']['seat']) != "")< $form->set_volunteer($_SESSION['volunteer']); header('location: /branch/menus.php'); exit(); > > > > ?> 

Are you sure you are in the right file? Usually you only get a warning like that on the header() or setcookie() function.

/. /Sites/st.ambulance/resources/controllers/tables_.php on line 47 is the more relevant part of the code. That is where the command that actually produces the error is. Please paste in that part as well, and we can probably help more thoroughly.

As I suggested in my answer. the code you’ve posted still doesn’t illustrate the order in which the view and controller are being run. Whatever is responsible for loading those files is where you’re fault lies.

2 Answers 2

Line 47 modifies the response headers:

header('location: /branch/menus.php'); //line 47 

Line 47 cannot be executed because the headers have already been sent, which happened to occur on line 32. All that happened on line 32 was that PHP decided it had enough content in the response to start sending it back to the browser.

Generally, if you want to modify the headers (whatever you’re doing on line 47), you need to do it at the very beginning of the file.

This is a good time to learn about the MVC design pattern — it would eliminate the possibility of this issue in the future. In MVC, the Controller executes first, and prepares everything for the View. So, you can modify your headers all you want in the Controller, and they won’t be sent until during or after the View is processed.

EDIT: It looks like you are using MVC, but somehow your view is executing before the controller has started (or perhaps finished). that shouldn’t happen! Unfortunately, the code you’ve posted doesn’t illustrate how either the controller or view are being accessed. but they’re being accessed out of order.

As TRiG point out in the comments below, you probably want to insert an exit() statement after line 47 as follows:

header('location: /branch/menus.php'); //line 47 exit(); 

This will cause the server to immediately send the Location redirect to the browser, and the request/response cycle is complete. All your header(‘Location: . ‘); calls should be immediately followed by exit(); . This doesn’t fix the issue at hand, but it is very important.

Источник

Warning: Cannot modify header information — headers already sent by ERROR [duplicate]

I’ve been struggling with this error for a while now. To start with, I just thought it was white space, but after further research I think it might be a problem similar to this:

Look for any statements that could send output to the user before this header statement. If you find one or more, change your code to move the header statement before them. Complex conditional statements may complicate the issue, but they may also help solve the problem. Consider a conditional expression at the top of the PHP script that determines the header value as early as possible and sets it there.

I’m guessing the include header is causing the problem along with the header(), but I’m not sure how to rearrange the code to get rid of this error. How do I remove the error?

 elseif($username == 'admin') < header("Location:admin.php"); >elseif($username == '') < header("Location:index.php"); >else die ("

Invalid username or password.

"); if ($username == "" || $token == "") < echo "

Please enter your username and password

"; > else < $query = "SELECT * FROM members WHERE username='$username'AND password = '$token'"; //Look in table for username entered $result = mysql_query($query); if (!$result) die ("Database access failed: " . mysql_error()); elseif (mysql_num_rows($result) >0) < $row = mysql_fetch_row($result); $_SESSION['username'] = $username; //Set session variables $_SESSION['password'] = $token; $fName = $row[0]; >> ?>

Place include_once ‘header.php’; after the if ($username. if/else chain so the redirection headers are not called after the HTML header is output.

Thanks for the replies. I moved the include header below the headers() and I’m not getting the errors. However, the header file includes the menu options for each location so as I’ve moved the include header below the headers() the menu options are not changing.

4 Answers 4

The long-term answer is that all output from your PHP scripts should be buffered in variables. This includes headers and body output. Then at the end of your scripts do any output you need.

The very quick fix for your problem will be to add

as the very first thing in your script, if you only need it in this one script. If you need it in all your scripts add it as the very first thing in your header.php file.

This turns on PHP’s output buffering feature. In PHP when you output something (do an echo or print) it has to send the HTTP headers at that time. If you turn on output buffering you can output in the script but PHP doesn’t have to send the headers until the buffer is flushed. If you turn it on and don’t turn it off PHP will automatically flush everything in the buffer after the script finishes running. There really is no harm in just turning it on in almost all cases and could give you a small performance increase under some configurations.

If you have access to change your php.ini configuration file you can find and change or add the following

This will turn output buffering out without the need to call ob_start().

Источник

Читайте также:  Php скрипт как сервис
Оцените статью