How can headers being sent before setting a cookie impact the functionality of a PHP script?

Sending headers before setting a cookie can cause the cookie to not be set properly since headers must be sent before any output. To solve this issue, make sure to set cookies before sending any headers or output to the browser.

<?php
// Set cookie before any output
setcookie("user", "John Doe", time() + 3600);

// Send headers after setting the cookie
header('Location: profile.php');
exit;
?>