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

One common pitfall to avoid when handling file uploads in PHP forms is not validating the file type and size before processing the upload. This can lead to security vulnerabilities and potential server overload. To mitigate this risk, always check the file type and size before moving the uploaded file to the server.

// Validate file type and size before processing the upload
$allowedFileTypes = ['jpg', 'jpeg', 'png', 'gif'];
$maxFileSize = 5 * 1024 * 1024; // 5MB

if (in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowedFileTypes) && $_FILES['file']['size'] <= $maxFileSize) {
    // 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';
}