What are the best practices for handling image rotation in PHP to ensure proper display on a webpage?

When handling image rotation in PHP to ensure proper display on a webpage, it is important to maintain the correct orientation of the image based on its EXIF data. This can be achieved by checking the orientation tag of the image and rotating it accordingly using PHP's GD library. By doing this, you can prevent images from being displayed incorrectly on the webpage.

// Load the image
$image = imagecreatefromjpeg('image.jpg');

// Get the EXIF data of the image
$exif = exif_read_data('image.jpg');

// Check the orientation tag
$orientation = $exif['Orientation'];

// Rotate the image based on the orientation
switch ($orientation) {
    case 3:
        $image = imagerotate($image, 180, 0);
        break;
    case 6:
        $image = imagerotate($image, -90, 0);
        break;
    case 8:
        $image = imagerotate($image, 90, 0);
        break;
}

// Display the rotated image
header('Content-Type: image/jpeg');
imagejpeg($image);

// Free up memory
imagedestroy($image);