What are some potential security risks when using absolute paths in PHP for file downloads?
Using absolute paths in PHP for file downloads can pose security risks by exposing sensitive server information and potentially allowing unauthorized access to files outside of the intended directory. To mitigate this risk, it is recommended to use relative paths instead, which limits access to files within the specified directory.
<?php
// Example of using relative path for file download
$filePath = 'downloads/example.pdf';
if (file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . basename($filePath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
} else {
echo 'File not found.';
}
?>