What best practices should be followed when handling image uploads and resizing in PHP?

When handling image uploads and resizing in PHP, it is important to validate the uploaded file to ensure it is actually an image file, sanitize the file name to prevent security vulnerabilities, and resize the image to a desired dimension to optimize loading time and storage space.

// Validate uploaded file as image
if (isset($_FILES['image'])) {
    $file = $_FILES['image'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
    
    if (in_array($file['type'], $allowed_types)) {
        // Sanitize file name
        $file_name = preg_replace("/[^A-Za-z0-9.]/", '', $file['name']);
        
        // Resize image
        list($width, $height) = getimagesize($file['tmp_name']);
        $new_width = 300;
        $new_height = ($height / $width) * $new_width;
        $resized_image = imagecreatetruecolor($new_width, $new_height);
        $image = imagecreatefromjpeg($file['tmp_name']);
        imagecopyresampled($resized_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        imagejpeg($resized_image, 'uploads/' . $file_name, 80);
        
        imagedestroy($image);
        imagedestroy($resized_image);
    }
}