Warning: session_start(): Cannot send session cookie – headers already sent

by Yang Yang on May 15, 2008

in PHP Tips & Tutorials

It is known that you have to make sure nothing’s already sent to output to perform a successful http header modification. As such, in PHP, you will keep an eye on possible white spaces before the use of header() function to modify delivery headers. For example,
<?php
header('...');
?>

this tiny snippet would fail if unscrupulous white spaces were prepended before the ‘<?php’ tag.

So upon error of Warning: session_start(): Cannot send session cookie – headers already sent, you should first check if there’s additional unwanted white spaces before calling session_start().

If this didn’t work for you. The second approach definitely would.

So you are calling session_start() from an included / required file, such as:

1.php
<?php
require_once('2.php');
?>

2.php
<?php
session_start();
?>

PHP works in a way that adds unexpected characters if you are including files, to make sure the header is sent successfully you’ll have to suppress the output using output buffer control in PHP. Just add the 2 lines in 1.php and you’ll be fine:

1.php
<?php
ob_start(); // start manual output buffer control
require_once('2.php');
ob_end_clean(); // manually erase the output buffer without sending it to client
?>

That’s it! Hopefully it’s solved at your end!

Related Posts

{ 1 comment… read it below or add one }

mrbigguy December 15, 2008 at 3:31 am

thanks for this mate… i get similiar problem in one of my site.. :)

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: