What are some best practices for handling file uploads and image processing in PHP to avoid errors like black or pixelated thumbnails?

When handling file uploads and image processing in PHP, it is important to ensure that the uploaded images are properly resized and processed to avoid issues like black or pixelated thumbnails. One way to achieve this is by using PHP's GD library to resize and create thumbnails of the uploaded images.

// Check if file is uploaded successfully
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $image = $_FILES['image']['tmp_name'];
    
    // Create a thumbnail of the uploaded image
    $thumbnail = imagecreatetruecolor(100, 100);
    $source = imagecreatefromjpeg($image);
    imagecopyresized($thumbnail, $source, 0, 0, 0, 0, 100, 100, imagesx($source), imagesy($source));
    
    // Save the thumbnail
    imagejpeg($thumbnail, 'thumbnails/' . $_FILES['image']['name']);
    
    // Free up memory
    imagedestroy($source);
    imagedestroy($thumbnail);
}