What are the best practices for handling file uploads in PHP applications, especially when dealing with large files?
When handling file uploads in PHP applications, especially with large files, it is important to set appropriate PHP configuration settings, validate file types and sizes, and handle file uploads securely to prevent security vulnerabilities such as file injection attacks.
// Set maximum file size for uploads
ini_set('upload_max_filesize', '20M');
// Validate file type and size
if ($_FILES['file']['type'] != 'image/jpeg' || $_FILES['file']['size'] > 2097152) {
die('Invalid file type or size.');
}
// Move uploaded file to a secure location
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo 'File uploaded successfully.';
} else {
echo 'Failed to upload file.';
}