How can PHP be used to prevent directory traversal attacks when downloading files?

Directory traversal attacks can be prevented in PHP when downloading files by using the basename() function to extract the filename from the provided path. This function removes any directory information and only returns the base name of the file, preventing attackers from accessing files outside of the intended directory.

$filename = basename($_GET['file']);
$filepath = '/path/to/files/' . $filename;

if (file_exists($filepath)) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    readfile($filepath);
} else {
    echo 'File not found';
}