What are the potential security risks of using PHP scripts to handle file downloads?
One potential security risk of using PHP scripts to handle file downloads is the possibility of allowing unauthorized users to access sensitive files on the server. To mitigate this risk, it is important to implement proper authentication and authorization checks before allowing a file download request to be processed.
<?php
// Check if user is authenticated and authorized to download the file
if (isset($_SESSION['user_id']) && $_SESSION['user_role'] == 'admin') {
$file = 'path/to/file.pdf';
// Check if the file exists
if (file_exists($file)) {
// Set appropriate headers for file download
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Length: ' . filesize($file));
// Read the file and output its contents
readfile($file);
exit;
} else {
echo 'File not found.';
}
} else {
echo 'Unauthorized access.';
}
?>
Related questions
-
PHP query string variables
-
PHP save image server
-
singletons dependency injection PHP