What are the potential pitfalls of mixing absolute paths with web paths in PHP download scripts?
Mixing absolute paths with web paths in PHP download scripts can lead to security vulnerabilities such as directory traversal attacks. To avoid this issue, it is important to ensure that only files within the specified download directory are accessible. One way to do this is by using PHP's realpath() function to convert the web path to an absolute path and then checking if the resulting path is within the download directory.
<?php
$downloadDir = '/path/to/download/directory';
$webPath = $_GET['file'];
$filePath = realpath($downloadDir . '/' . $webPath);
if (strpos($filePath, $downloadDir) === 0 && file_exists($filePath)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
readfile($filePath);
} else {
echo 'File not found';
}
?>
Related Questions
- How can PHP arrays be effectively used to streamline the process of saving form values from a PHP form?
- What is the correct syntax for splitting a string by newline characters in PHP using the explode() function?
- How can the COUNT() function be used in PHP to determine the number of occurrences of a specific value in a database query?