How to resolve the error "Can not modify header information already sent by" in PHP? [duplicate]

0

Because when we use header() and setcookie() error occurs:

  

Warning: Can not modify header information - headers already sent by ( output started at /teste.php:10 ) in /teste.php on line 21

Why does this error happen? How to solve?

    
asked by anonymous 11.03.2014 / 21:51

2 answers

6

In fact, it is not a mistake. It is a warning.

This is done when your browser makes a request to the web server. With the web server response. It gives you a response header ( header ). This header contains information about page encoding, page size, cache lifetime, last update time, and everything that is relevant, from a web page to a browser.

When you read "headers already sent" it means that the server already sent the header and AFTER this send you are trying to change some information that should be sent in the header.

But if you are not manipulating anything that comes in header . You did nothing and you're getting this error.

In PHP the header begins to be sent as soon as you enter the first HTML character. Be it outside PHP or within PHP code with an echo or print ().

<?php
  $numero_1 = 5;
  echo $numero_1;
?>

Everything outside the PHP code is HTML, a space on line 1 before opening PHP code would be the reason for a response to the client. Any function, session, cookie would cause error.

To fix this warning. You would have to put all the code that works with session, cookie, redirects, etc ... before any HTML pro character. No attempt to set / create a cookie after sending a "Hello world" message to the browser.

If you need to set / create a cookie before sending a "Hello World" message or anything, rethink what you are doing.

    
11.03.2014 / 22:35
2

It depends, if you are editing with DreamWeaver it adds to your files when saving an option called GOOD CODING (something of the type), this prevents your PHP scripts from running properly on linux servers, on windows it works normally. Otherwise, see if checks in php like:

<?php
if(isset($_POST['teste'])){
  header("Location: index.php");
  // é essencial utilizar o exit() após um redireccionamento com header() para evitar possíveis erros
  exit();
}
?>

And other checks are in the header of the page, ie the lines that make a check / redirect should always be above the code, always with the tags at the beginning of the HTML page. Forms, texts, etc., can never be above php when redirects are made. Always up. Post your code to us which makes it easier to help.

    
11.03.2014 / 23:55