What potential pitfalls should be considered when allowing users to upload files to a website using PHP?

One potential pitfall when allowing users to upload files to a website using PHP is the risk of malicious files being uploaded, which could be executed on the server. To prevent this, it is important to validate the file type and size before allowing the upload. Additionally, storing the uploaded files in a separate directory outside of the web root can help prevent direct access to the files.

// Check file type and size before allowing upload
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxFileSize = 5242880; // 5MB

if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxFileSize) {
    // Move the uploaded file to a secure directory
    move_uploaded_file($_FILES['file']['tmp_name'], '/path/to/uploads/' . $_FILES['file']['name']);
    echo 'File uploaded successfully!';
} else {
    echo 'Invalid file type or size. Please try again.';
}