Fix warning: Headers already sent - setcookie error in PHP

After some modifications on my website, I am receiveing error notification:

Warning: Cannot modify header information - headers already sent by (output started at /www/b/i/u50034/public_html/index.php:965) in /www/b/i/u50034/public_html/index.php on line 1006

I found out that error is caused by setcookie(). In code, everything seems to be correct. Do you know how to fix it and make it work properly ?
posted on 12.07.2019 at 18:51
0pnshow more
onefiveonefive
Hi,

To fix the error, the setcoookie() function has to be moved before HTML content.

The description of setcookie() function:
Setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction).

So instead of something like this:

<?php

$cookie_name = "abc";
$cookie_value = "12345";

?>

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>

<?php

setcookie($cookie_name, $cookie_value, time() + 3600, "/");

?>

</body>
</html>


You have to use this:

<?php

$cookie_name = "abc";
$cookie_value = "12345";

setcookie($cookie_name, $cookie_value, time() + 3600, "/");

?>

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>

</body>
</html>

posted on 21.07.2019 at 10:15
0pnshow more
TimTim
share on facebookshare on twitter
2020 AnswerTabsTermsContact us
This site uses cookies to improve your experience, for analytics and ads. By continuing to browse this site you agree to our use of cookies.