-1

Php Doc Says:

  • "Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from
    PHP."

  • " This requires that you place calls to setcookie() prior to any output, including and tags as well as any whitespace."

I understand the importance of above mentioned requirements but how is the code below running without throwing "Headers already Sent" error?

          <html>
          <body>
          <h1>Hey</h1>
          
          <?php
              echo "Hello";
              setcookie("hey","hellocookie");
              //header("Pragma: no-cache");
              //echo $_COOKIE['hey'];
              header('Location: http://www.example.com/');
          ?>
          </body>
          </html>

header('Location: http://www.example.com/'); works without throwing errors. Also, setcookie("hey","hellocookie"); works even though there's an output echo "Hello"; prior to it. I tested it with echo $_COOKIE['hey']; and it does print heycookie.

*Note: Running the above script on Localhost/Xampp. Error Reporting is not disabled. I do get an error on browser output if I miss one of those semi-colons. *

Mathews Mathai
  • 1,707
  • 13
  • 31

1 Answers1

1

Any of those functions that works with headers MUST be used before any kind of output is sent... even single white space raise such PHP error.

PHP header() documentation

ino
  • 2,345
  • 1
  • 15
  • 27
  • Even `header("Pragma: no-cache");` worked without errors. – Mathews Mathai Mar 22 '18 at 20:23
  • Turn on the [PHP Error Reporting](https://stackoverflow.com/a/21429652/1456401)! – ino Mar 22 '18 at 20:24
  • I added `ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);` in my code but it still gives no error. – Mathews Mathai Mar 22 '18 at 20:26
  • Make sure your web server has full error reporting on, ie E_ALL even in your config files. It fires a `PHP Warning`. – ino Mar 22 '18 at 20:29
  • If it did throw an error, how come `echo $_COOKIE['hey'];`is printing the cookie value? It is not suppose to be set if there's an error, right? – Mathews Mathai Mar 22 '18 at 20:34
  • It is "just" a warning - the script will continue... – ino Mar 22 '18 at 20:35
  • So `setcookie` will work even if I use it after an output statement. I think I got it now. Thanks. I thought it won't work at all and cookie won't be set since header is `sent` already. – Mathews Mathai Mar 22 '18 at 20:38
  • Avoid using code that is raising errors even warnings since you can get unexpected results. – ino Mar 22 '18 at 20:39
  • Got it :D I was just exploring `headers` and `cookies` to make use of them more efficiently. Been reading about it a lot and was surprised to find this working. Just wanted to know if there's an exception. – Mathews Mathai Mar 22 '18 at 20:42