What are the potential pitfalls when handling file uploads in PHP?

One potential pitfall when handling file uploads in PHP is not properly validating the file type and size, which can lead to security vulnerabilities such as allowing malicious files to be uploaded or overwhelming the server with large files. To mitigate this risk, always validate the file type and size before processing the upload.

// Validate file type and size before processing the upload
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 2 * 1024 * 1024; // 2MB

if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
    // Process the file upload
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    echo 'File uploaded successfully!';
} else {
    echo 'Invalid file type or size. Please upload a JPEG or PNG file under 2MB.';
}