What are the best practices for handling file uploads and renaming files in PHP, especially in the context of generating thumbnails?

When handling file uploads in PHP, it's important to validate the file type and size to prevent security vulnerabilities. Renaming uploaded files can also help prevent conflicts and ensure unique filenames. When generating thumbnails, consider using libraries like GD or Imagick to resize and create the thumbnails efficiently.

// Handle file upload and renaming
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    $fileName = uniqid() . '_' . $_FILES['file']['name'];
    $targetPath = $uploadDir . $fileName;

    if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
        // File uploaded successfully, continue with thumbnail generation
    } else {
        echo 'File upload failed.';
    }
}

// Generate thumbnail using GD library
$thumbnailPath = 'thumbnails/' . 'thumb_' . $fileName;
list($width, $height) = getimagesize($targetPath);
$newWidth = 100;
$newHeight = 100;
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$image = imagecreatefromjpeg($targetPath);
imagecopyresized($thumb, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($thumb, $thumbnailPath);
imagedestroy($thumb);
imagedestroy($image);