What potential security risks should be considered when setting up a PHP server for file downloads?
One potential security risk when setting up a PHP server for file downloads is the possibility of allowing unauthorized access to sensitive files on the server. To mitigate this risk, it is important to properly validate user input and restrict access to only authorized users. Additionally, implementing proper file path sanitization and using secure download links can help prevent direct access to files.
<?php
// Validate user input to ensure only authorized users can access files
if ($_SESSION['logged_in'] !== true) {
header('HTTP/1.1 403 Forbidden');
exit;
}
// Sanitize file path to prevent directory traversal attacks
$filename = basename($_GET['file']);
$filepath = '/path/to/files/' . $filename;
// Check if file exists and is within the allowed directory
if (file_exists($filepath) && strpos(realpath($filepath), '/path/to/files/') === 0) {
// Set appropriate headers for file download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filepath);
} else {
header('HTTP/1.1 404 Not Found');
exit;
}
?>