What best practices should be followed when handling file uploads in PHP to ensure successful execution?
When handling file uploads in PHP, it is important to follow best practices to ensure successful execution. This includes setting appropriate file upload limits, validating file types and sizes, and securely storing uploaded files to prevent security vulnerabilities.
// Set maximum file size limit
ini_set('upload_max_filesize', '10M');
// Validate file type and size
$allowed_types = ['image/jpeg', 'image/png'];
$max_size = 5 * 1024 * 1024; // 5MB
if (!in_array($_FILES['file']['type'], $allowed_types) || $_FILES['file']['size'] > $max_size) {
// Handle invalid file type or size
}
// Securely store uploaded file
$upload_dir = 'uploads/';
$upload_file = $upload_dir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
// File uploaded successfully
} else {
// Handle file upload error
}