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';
}
?>