0

I have been told when output something like echo/var_dump before header() or session_start, a warning will be shown like this "php Cannot send session cookie-headers already sent by".

But the following code works fine. It is strange! Who can tell me the reason? PHP version is 5.6.9

<?php 
echo 'hello';
setcookie('a','a');
session_start();
$_SESSION['a'] = 'a';
header("location:test.php");
?>
jeroen
  • 91,079
  • 21
  • 114
  • 132
Will Yun
  • 105
  • 1
  • 1
  • 9
  • 1
    Most likely it's because of [output_buffering](http://php.net/manual/en/outcontrol.examples.basic.php) as [mentioned here](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php?rq=1) (It's a bit down in the answer - _Bring a shovel cause you'll need to dig_). – Epodax May 04 '16 at 06:54
  • You said 'following code'. Where is it? – VipindasKS May 04 '16 at 06:54
  • 1
    @Epodax A bit down? More like buried :-) – jeroen May 04 '16 at 06:55
  • On web or on local machine? – Andreas May 04 '16 at 07:13

1 Answers1

2

If you use output_buffering = On in your php.ini you can send cookies after the headers have been sent.

As stated in php.ini comment :

Output buffering allows you to send header lines (including cookies) even after you send body content, at the price of slowing PHP's output layer a bit. You can enable output buffering during runtime by calling the output buffering functions. You can also enable output buffering for all files by setting this directive to On. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096).

eol
  • 23,236
  • 5
  • 46
  • 64