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 ? | |||||||||||
| |||||||||||
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> | |||||||||||
| |||||||||||
| |||||||||||
![]() ![]() | |||||||||||
2021 AnswerTabs | Terms | Contact us |