Skip to content
PHP Logo

How can the issue of headers being sent before setcookie() in PHP be resolved to prevent errors?

Issue: The error of "headers already sent" in PHP occurs when the setcookie() function is called after any output (like HTML, whitespace, or even a newline) has been sent to the browser. To prevent this error, ensure that setcookie() is called before any output is sent to the browser.

php
<?php
// Ensure setcookie() is called before any output
ob_start();
setcookie('cookie_name', 'cookie_value', time() + 3600, '/');
ob_end_flush();
?>