What are potential pitfalls when uploading files using PHP?

One potential pitfall when uploading files using PHP is not properly validating the file type and size, which can lead to security vulnerabilities such as allowing malicious files to be uploaded. To solve this, always validate the file type and size before allowing the upload to proceed.

// Validate file type and size before uploading
$allowedFileTypes = ['jpg', 'jpeg', 'png', 'gif'];
$maxFileSize = 5 * 1024 * 1024; // 5MB

if (!in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowedFileTypes)) {
    die('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.');
}

if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size is too large. Maximum file size allowed is 5MB.');
}

// Proceed with file upload
// Your file upload code here