How can I resolve the "Cannot modify header information - headers already sent" error when using session_start() and setcookie() in PHP?
The "Cannot modify header information - headers already sent" error occurs when PHP tries to send headers, such as those set by session_start() or setcookie(), after output has already been sent to the browser. To resolve this issue, make sure that no output is sent before calling functions that modify headers.
<?php
ob_start(); // Start output buffering
// Your PHP code here
session_start(); // Start the session
// Set a cookie
setcookie("cookie_name", "cookie_value", time() + 3600);
ob_end_flush(); // End output buffering and send output to the browser
?>
Related Questions
- What are the best practices for handling LDAP connections in PHP scripts for interacting with Active Directory on a Windows Server?
- How can PHP variables be properly passed in a link within a script?
- Are there any best practices for including scripts in PHP to avoid conflicts with jQuery plugins like "Ingrid"?