How can PHP be used to detect and correct image orientation issues during file upload processes?

Image orientation issues can occur when users upload images taken with smartphones or cameras that store orientation metadata. This metadata can cause the image to appear rotated incorrectly. To detect and correct these orientation issues during file upload processes, PHP can be used to read the image metadata and apply the necessary rotation.

// Check if the uploaded file is an image
if(isset($_FILES['image']) && $_FILES['image']['error'] == 0){
    $image = $_FILES['image']['tmp_name'];
    
    // Get the image orientation from metadata
    $exif = exif_read_data($image);
    $orientation = isset($exif['Orientation']) ? $exif['Orientation'] : 0;
    
    // Rotate the image based on orientation
    $img = imagecreatefromstring(file_get_contents($image));
    switch($orientation){
        case 3:
            $img = imagerotate($img, 180, 0);
            break;
        case 6:
            $img = imagerotate($img, -90, 0);
            break;
        case 8:
            $img = imagerotate($img, 90, 0);
            break;
    }
    
    // Save the corrected image
    imagejpeg($img, 'corrected_image.jpg');
}