What is the correct placement for setting cookies in a PHP script?

When setting cookies in a PHP script, it is important to do so 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. Therefore, it is recommended to set cookies at the beginning of your PHP script, before any HTML or text content.

<?php
// Set cookies before any output
setcookie("user", "John Doe", time() + 3600, "/");
setcookie("email", "john.doe@example.com", time() + 3600, "/");

// Output content after setting cookies
echo "Cookies have been set!";
?>