What are best practices for handling image uploads and generating thumbnails in PHP using the GD library?

When handling image uploads in PHP, it is important to validate the file type and size to prevent security vulnerabilities. To generate thumbnails using the GD library, you can resize the uploaded image and save it as a new file. This helps improve page load times by displaying smaller versions of images.

// Validate uploaded image file
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $fileType = $_FILES['image']['type'];
    $fileSize = $_FILES['image']['size'];
    
    if (($fileType == 'image/jpeg' || $fileType == 'image/png') && $fileSize < 5000000) {
        // Resize and generate thumbnail
        $image = imagecreatefromjpeg($_FILES['image']['tmp_name']);
        $thumb = imagecreatetruecolor(100, 100);
        imagecopyresampled($thumb, $image, 0, 0, 0, 0, 100, 100, imagesx($image), imagesy($image));
        
        // Save thumbnail
        imagejpeg($thumb, 'thumbnails/thumb_' . $_FILES['image']['name'], 80);
        
        // Free up memory
        imagedestroy($image);
        imagedestroy($thumb);
    } else {
        echo 'Invalid file type or size. Please upload a JPEG or PNG image less than 5MB.';
    }
} else {
    echo 'Error uploading file.';
}