What is the correct placement for the header() function in PHP when generating an image?
When generating an image in PHP, it is important to set the correct content type using the header() function before outputting any image data. This ensures that the browser interprets the data correctly as an image. The header() function should be placed before any output, including any HTML or whitespace, to avoid any errors.
<?php
// Set the content type to image/jpeg
header('Content-Type: image/jpeg');
// Create and output the image
$im = imagecreatefromjpeg('example.jpg');
imagejpeg($im);
imagedestroy($im);
?>