What is the issue with setting cookies in PHP and how can it lead to "Headers already sent" errors?

Setting cookies in PHP must be done before any output is sent to the browser, as headers must be sent before any content. If cookies are set after content has already been sent, it will result in a "Headers already sent" error. To solve this issue, make sure to set cookies at the beginning of your PHP script, before any HTML or text output.

<?php
// Start the session before any output
session_start();

// Set a cookie
setcookie("username", "JohnDoe", time() + 3600);

// Rest of your PHP code goes here
?>