I've created an upload script which also creates a thumbnail which works fine, but I've now encountered a problem. When I upload some images the exif orientation data automatically rotates the image on my website.

I've tried searching online on how to check for the data and rotate it back if there is any but I can't understand what I'm meant to do.

Here is my code so far:

PHP Code:
if(isset($_POST['submit'])) {
            
$allowedExts = array("jpg""jpeg""gif""png""JPG""GIF");
            
$extension end(explode("."strtolower($_FILES["file"]["name"])));
            if (((
$_FILES["file"]["type"] == "image/gif")
            || (
$_FILES["file"]["type"] == "image/jpeg")
            || (
$_FILES["file"]["type"] == "image/png")
            || (
$_FILES["file"]["type"] == "image/pjpeg"))
            && 
in_array($extension$allowedExts)) {
                if (
$_FILES["file"]["error"] > 0) {
                    echo 
"Return Code: " $_FILES["file"]["error"] . "<br>";
                } else {
            
                    
$random_numer rand(1000000099999999);
                    
$newname1 $random_numer $_FILES["file"]["name"];
                    
$scramble md5($newname1);
                    
$extension end(explode("."$_FILES["file"]["name"]));
                    
$final_name $scramble "." $extension;

                    
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/gallery/" $final_name);
                    
create_thumbnail($final_name);
                    
$stmt $conn->prepare('INSERT INTO gallery (image) VALUES (:image)');
                    
$stmt->bindParam(':image'$final_name);
                    
$stmt->execute();
                    
                    if (
$stmt->rowCount() > 0) {
                        echo 
"<p class='success'>The Image has been added!
                         <a href='gallery.php'>Please click here to refresh</a></p>"
;
                    } else {
                        echo 
"<p class='error'>The Image was not added, there was an error.</p>";
                    }
                    
                }
            } else {
                echo 
"Invalid file";
            }
        } 
I've tried to create functions that rotate the image if the exif data it present but I can't seem to get anything to work. Can someone please show me how to do it!?