What are the potential pitfalls of using PHP for file uploads, especially with larger files?
When using PHP for file uploads, especially with larger files, there are potential pitfalls such as running into memory limits, execution time limits, and potential security vulnerabilities. To avoid these issues, it is important to properly configure PHP settings, validate file types and sizes, and use server-side validation to prevent malicious uploads.
// Increase memory limit and execution time for large file uploads
ini_set('memory_limit', '256M');
ini_set('max_execution_time', 300);
// Validate file type and size before uploading
$allowedFileTypes = ['pdf', 'doc', 'docx'];
$maxFileSize = 10 * 1024 * 1024; // 10 MB
if (in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowedFileTypes) && $_FILES['file']['size'] <= $maxFileSize) {
// Upload file to server
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
} else {
echo 'Invalid file type or size.';
}