What are some common pitfalls when using the header() function to set content types in PHP?

One common pitfall when using the header() function to set content types in PHP is that headers must be set before any output is sent to the browser. If output has already been sent, attempting to set headers will result in an error. To avoid this issue, make sure to set headers at the beginning of your PHP script, before any HTML or text is echoed.

<?php
// Set content type before any output
header('Content-Type: text/html');

// Your PHP code here
echo "<html><body><h1>Hello, World!</h1></body></html>";
?>