What are best practices for dynamically generating links to listed files in PHP based on their file names?

When dynamically generating links to listed files in PHP based on their file names, it is important to sanitize the file names to prevent any security risks such as directory traversal attacks. One way to do this is by using PHP's `basename()` function to extract the base name of the file, which removes any directory paths. Additionally, you can use `urlencode()` to encode the file name for safe inclusion in URLs.

<?php
// List of files
$files = array("file1.txt", "../file2.txt", "file3.pdf");

// Loop through the files and generate links
foreach ($files as $file) {
    $fileName = basename($file);
    $url = 'http://example.com/files/' . urlencode($fileName);
    echo "<a href='$url'>$fileName</a><br>";
}
?>