What are the potential pitfalls of setting cookies before the header and body in PHP?

Setting cookies before the header and body in PHP can lead to headers already being sent error, as cookies must be set before any output is sent to the browser. To solve this issue, cookies should be set before any HTML content or headers are sent.

<?php
// Set cookies before any output
setcookie("user", "John Doe", time() + 3600, "/");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Setting Cookies</title>
</head>
<body>
    <h1>Cookies set successfully!</h1>
</body>
</html>