What are some best practices for handling file uploads in PHP, especially when files are uploaded from external programs?
When handling file uploads in PHP, especially when files are uploaded from external programs, it is important to validate and sanitize the file input to prevent security vulnerabilities such as file injection attacks. Additionally, it is recommended to store uploaded files outside of the web root directory to prevent direct access to them. Finally, consider implementing file size and file type restrictions to ensure that only valid files are uploaded.
<?php
// Check if file was uploaded
if(isset($_FILES['file'])){
$file = $_FILES['file'];
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if(!in_array($file['type'], $allowedTypes)){
die('Invalid file type.');
}
// Validate file size
if($file['size'] > 5000000){
die('File is too large.');
}
// Sanitize file name
$fileName = preg_replace("/[^A-Za-z0-9.]/", '', $file['name']);
// Move file to secure directory
move_uploaded_file($file['tmp_name'], '/path/to/secure/directory/' . $fileName);
}
?>