Skip to content
PHP Logo

How can the error "Cannot modify header information" be resolved when setting cookies in PHP?

The error "Cannot modify header information" occurs in PHP when trying to set cookies after headers have already been sent to the browser. To resolve this issue, make sure that all cookie-setting functions are called before any output is sent to the browser, including HTML, whitespace, or error messages.

php
<?php
// Ensure no output has been sent to the browser before setting cookies
ob_start();

// Set cookies
setcookie("cookie_name", "cookie_value", time() + 3600, "/");
setcookie("another_cookie", "another_value", time() + 3600, "/");

// Send output to the browser
ob_end_flush();
?>