What is the correct placement for the header() function in PHP image creation scripts?
When creating images dynamically in PHP, it is important to set the correct headers before outputting any image data. This is done using the header() function with the Content-Type header set to the appropriate image type (e.g., image/jpeg, image/png). Failure to set the correct headers can result in the image not being displayed correctly in the browser.
<?php
// Set the content type header to specify the image type
header('Content-Type: image/jpeg');
// Create a new image resource
$image = imagecreate(200, 200);
// Set the background color to white
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
// Output the image as a JPEG
imagejpeg($image);
// Clean up resources
imagedestroy($image);
?>