What are best practices for setting cookies in PHP to avoid header modification errors?
When setting cookies in PHP, it's important to ensure that no output has been sent to the browser before setting the cookie. This is because setting cookies requires modifying the HTTP headers, and any output sent before that will result in a "headers already sent" error. To avoid this issue, it's best practice to set cookies before any HTML or whitespace in your PHP script.
<?php
// Check if headers have been sent
if (!headers_sent()) {
// Set the cookie
setcookie("cookie_name", "cookie_value", time() + 3600, "/");
}
?>