How can one properly set a cookie in PHP without encountering header modification errors?

When setting a cookie in PHP, it must be done before any output is sent to the browser. This is because cookies are sent in the HTTP header, which must be set before any content is sent. To avoid encountering header modification errors, make sure to set cookies at the very beginning of your PHP script, before any HTML or whitespace.

<?php
// Set cookie at the beginning of the script
setcookie("cookie_name", "cookie_value", time() + 3600, "/");
?>