What are common pitfalls when using PHP for file uploads and resizing images?

Common pitfalls when using PHP for file uploads and resizing images include not validating file types, not checking for file size limits, and not properly handling errors. To solve these issues, always validate file types before uploading, set file size limits to prevent large files from being uploaded, and handle errors gracefully to provide feedback to users.

// Validate file type before uploading
$allowedFileTypes = ['jpg', 'jpeg', 'png'];
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($extension, $allowedFileTypes)) {
    die('Invalid file type. Only JPG, JPEG, and PNG files are allowed.');
}

// Check for file size limits
$maxFileSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size exceeds limit. Please upload a smaller file.');
}

// Handle errors
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    die('File upload failed. Please try again.');
}

// Resize image (assuming GD extension is enabled)
$uploadedFile = $_FILES['file']['tmp_name'];
$resizedImage = imagecreatetruecolor(100, 100);
$source = imagecreatefromjpeg($uploadedFile);
imagecopyresampled($resizedImage, $source, 0, 0, 0, 0, 100, 100, imagesx($source), imagesy($source));
imagejpeg($resizedImage, 'resized_image.jpg');