What are the best practices for handling file uploads in PHP to prevent errors or security vulnerabilities?
When handling file uploads in PHP, it is important to validate and sanitize user input to prevent errors or security vulnerabilities. One common practice is to check the file type and size before processing the upload. Additionally, storing uploaded files outside the web root directory and generating unique file names can help prevent malicious attacks.
// Example of handling file uploads in PHP
// Check if file was uploaded without errors
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
// Validate file type
$allowed_types = ['image/jpeg', 'image/png'];
if (!in_array($_FILES['file']['type'], $allowed_types)) {
die('Invalid file type.');
}
// Validate file size
if ($_FILES['file']['size'] > 5000000) {
die('File is too large.');
}
// Move uploaded file to a secure location
$upload_dir = '/path/to/uploads/';
$file_name = uniqid() . '_' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir . $file_name);
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}