What are the recommended best practices for handling file uploads in PHP?
When handling file uploads in PHP, it is important to validate the file type and size to prevent security vulnerabilities such as file injection attacks. It is also recommended to store uploaded files outside of the web root directory to prevent direct access from the public. Additionally, consider renaming the file to prevent overwriting existing files with the same name.
<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$file = $_FILES['file'];
// Validate file type
$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
if(!in_array($file['type'], $allowed_types)){
die('Invalid file type. Allowed types: jpeg, png, gif');
}
// Validate file size (max 5MB)
if($file['size'] > 5 * 1024 * 1024){
die('File size exceeds limit of 5MB');
}
// Store file outside of web root directory
$upload_dir = 'uploads/';
$file_path = $upload_dir . basename($file['name']);
if(move_uploaded_file($file['tmp_name'], $file_path)){
echo 'File uploaded successfully!';
} else {
echo 'Error uploading file';
}
} else {
echo 'Error uploading file';
}
?>