What are common pitfalls to avoid when uploading files using PHP and HTML forms?
One common pitfall to avoid when uploading files using PHP and HTML forms is not properly checking the file type and size before allowing the upload. This can lead to security vulnerabilities and potential issues with server performance. To prevent this, always validate the file type and size before moving forward with the upload process.
// Check file type and size before uploading
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxSize = 5242880; // 5MB
if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
// Process 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 file that is a JPEG, PNG, or GIF and less than 5MB.';
}