How can user input validation be implemented to prevent malicious file downloads in PHP scripts?
- user input validation
- malicious file downloads
- PHP scripts
- security measures
- file upload vulnerability
User input validation can be implemented in PHP scripts by checking the file extension and content type before allowing a file to be downloaded. This can prevent malicious files from being downloaded onto the server or client machine.
// Check if the file extension and content type are valid before allowing download
$allowedExtensions = ['pdf', 'doc', 'docx', 'txt'];
$allowedContentTypes = ['application/pdf', 'application/msword', 'text/plain'];
$uploadedFile = $_FILES['file'];
if (in_array(pathinfo($uploadedFile['name'], PATHINFO_EXTENSION), $allowedExtensions) && in_array($uploadedFile['type'], $allowedContentTypes)) {
// Allow file download
header('Content-Type: ' . $uploadedFile['type']);
header('Content-Disposition: attachment; filename=' . $uploadedFile['name']);
readfile($uploadedFile['tmp_name']);
} else {
// Invalid file type, do not allow download
echo 'Invalid file type. Please upload a valid file.';
}
Related questions
-
JURI::current() Joomla 1.5 PHP
-
PHP JavaScript echo
-
SQL DISTINCT COUNT