Page 1 of 1

setcookie problem

Posted: Fri Apr 23, 2010 11:14 am
by Richard_in_Az
Using the following setcookie example from http://php.net/manual/en/function.setcookie.php
I get a warning error.
This is on a local machine using the Rapid PHP 2010 editor and server.

Code: Select all


$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1);

Warning: Cannot modify header information - headers alredy sent by (output started at C:\user\***\AppData\local\temp\prev0-.php:7) in {machine path} on line 4.


So why does their example fail to work?

Re: setcookie problem

Posted: Fri Apr 23, 2010 11:55 am
by phu
This error means you've sent output before attempting to set the cookie. Make sure you're doing this before any output is generated in your script (or any script included/required before this code executes).

This is often the result of closing a PHP tag at the end of a file and accidentally adding a line break afterwards (also, some editors do this automatically). One solution, which not everyone agrees with, is to avoid using end tags on your <?php tags in script-only files so that they will never generate an output line break.

Another, more hackish work-around (which is really just a band-aid until you can fix the real problem, i.e. "OH MY GOD THE SERVER IS DOWN DO SOMETHING NOW!"), is to invoke ob_start() at the very beginning of your script. It will buffer all output until the script completes; if you don't call the corresponding flush methods, they will be called implicitly when execution completes. When used properly, this is actually a slight speed optimization, but it shouldn't be used as a crutch.