What are the potential pitfalls of setting and redirecting cookies in PHP, especially across different pages on the same domain?

One potential pitfall of setting and redirecting cookies in PHP across different pages on the same domain is that the headers must be sent before any output is displayed to the browser. To ensure proper cookie handling, you can use output buffering to capture any output and prevent headers from being sent prematurely.

<?php
ob_start(); // Start output buffering

// Set cookie
setcookie("example_cookie", "value", time() + 3600, "/");

// Redirect to another page
header("Location: another_page.php");
exit();
ob_end_flush(); // Flush output buffer
?>