What are common pitfalls when trying to upload files using PHP on a web server?

Common pitfalls when uploading files using PHP on a web server include not setting the correct permissions on the upload directory, not properly validating file types and sizes, and not handling errors effectively. To solve these issues, make sure the upload directory has the correct permissions, validate file types and sizes before allowing the upload, and implement error handling to provide feedback to users.

<?php
$uploadDir = 'uploads/';
$allowedTypes = ['jpg', 'jpeg', 'png'];
$maxFileSize = 2 * 1024 * 1024; // 2MB

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];

    if ($file['error'] === UPLOAD_ERR_OK) {
        $fileExt = pathinfo($file['name'], PATHINFO_EXTENSION);

        if (in_array($fileExt, $allowedTypes) && $file['size'] <= $maxFileSize) {
            $uploadPath = $uploadDir . uniqid() . '.' . $fileExt;

            if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                echo 'File uploaded successfully!';
            } else {
                echo 'Error uploading file.';
            }
        } else {
            echo 'Invalid file type or size.';
        }
    } else {
        echo 'Error uploading file.';
    }
}
?>