The following code list all files in a folder and allows the user to download one of them. It is working but I think it could be done better.

Is there a way to reduce the number of forms to only one and to improve the way I retrieve the name of the file to download?

My second concern is about the security of my getFile function.

function listDir($directoryName) {$directory = opendir($directoryName);$files = array();
while ($elem = readdir($directory))
{
if ($elem != '.' &&$elem != '..' && $elem != '.htaccess') {$files[] = $elem; } } closedir(); if (!empty($directory))
{
sort($files); echo "<ul>"; foreach ($files as $file) {$filePath = $directoryName.'/'.$file;
echo "<form method='post' action=".htmlentities($_SERVER['PHP_SELF']).">"; echo "<li>($fileDate)";
echo "<input type='hidden' name='$file' value='$filePath'>";
echo " <button type='submit' name='getFile'>Télécharger</button> ";
echo "$file</li>"; echo "</form>"; } echo "</ul>"; } } function getFile($file)
{
if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file);
if (isset($_POST['getFile'])) {$keys = array_keys($_POST);$file = $_POST[$keys[0]];