What are common pitfalls when trying to upload files using PHP?

Common pitfalls when trying to upload files using PHP include not setting the correct permissions on the upload directory, not checking the file size before uploading, and not validating the file type. To solve these issues, make sure the upload directory has the correct permissions, check the file size before uploading, and validate the file type to ensure it is allowed.

// Ensure the upload directory has the correct permissions
$uploadDir = 'uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Check the file size before uploading
$maxFileSize = 10 * 1024 * 1024; // 10MB
if ($_FILES['file']['size'] > $maxFileSize) {
    echo 'File size exceeds limit';
    exit;
}

// Validate the file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
    echo 'Invalid file type';
    exit;
}

// Move the uploaded file to the upload directory
move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $_FILES['file']['name']);