What are best practices for validating and sanitizing user-uploaded files in a PHP application?
Validating and sanitizing user-uploaded files in a PHP application is crucial to prevent security vulnerabilities such as file injection attacks. To validate user-uploaded files, you should check the file type, size, and content to ensure they meet your application's requirements. Sanitizing involves removing any potentially harmful content from the file before storing it on the server.
// Validate and sanitize user-uploaded file
if(isset($_FILES['file'])){
$file = $_FILES['file'];
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if(!in_array($file['type'], $allowedTypes)){
die('Invalid file type. Only JPEG, PNG, and GIF files are allowed.');
}
// Validate file size
$maxFileSize = 1048576; // 1MB
if($file['size'] > $maxFileSize){
die('File is too large. Maximum file size allowed is 1MB.');
}
// Sanitize file content
$sanitizedContent = file_get_contents($file['tmp_name']);
// Save sanitized file to the server
$destination = 'uploads/' . $file['name'];
move_uploaded_file($file['tmp_name'], $destination);
echo 'File uploaded successfully.';
}