What are some common pitfalls to avoid when handling file uploads in PHP?

One common pitfall to avoid when handling file uploads in PHP is not properly validating the file type before allowing it to be uploaded. This can lead to security vulnerabilities such as allowing malicious files to be uploaded to the server. To solve this issue, always validate the file type against a list of allowed file extensions before moving the file to the upload directory.

$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
$uploadedFile = $_FILES['file']['name'];
$extension = pathinfo($uploadedFile, PATHINFO_EXTENSION);

if (!in_array($extension, $allowedExtensions)) {
    echo "Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.";
    exit;
}

// Move the file to the upload directory
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $uploadedFile);