Tuesday, 31 January 2017

php - setcookie, Cannot modify header information - headers already sent

Cookies are sent in the headers of the transmission of the HTTP page. Once you give some output, you cannot modify these anymore.



The problem in your case lies in you outputting some of the HTML-document before trying to set the cookie.



There are a few ways to solve it; one of which is setting the cookie prior to outputting anything on the page like so



    $value = 'something from somewhere';
setcookie("TestCookie", $value);
?>















Alternatively, you could buffer your output so that nothing gets written until you explicitly tell it to



    ob_start(); // Initiate the output buffer
?>









$value = 'something from somewhere';
setcookie("TestCookie", $value);
?>



ob_end_flush(); // Flush the output from the buffer
?>


For more information on this last approach, take a look at the ob_start and ob_end_flush functions.



It might be useful to read about setcookie, too.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...