submitted by: olaf
PHP: Open a directory
This simple function generates a select form element for all files of a given directory. Use this function together with the "Universal downloader" on this site. The function is modified to work with "register_globals = off "(since version 1.01). I changed the last version (1.02) to make this function more flexible. Use the modified function in forms to update dynamic image names in a database table.
code snippet:
<?php
function select_files($dir, $label = "", $select_name, $curr_val = "", $char_length = 30) {
$teller = 0;
if ($handle = opendir($dir)) {
$mydir = ($label != "") ? "<label for=\"".$select_name."\">".$label."</label>\n" : "";
$mydir .= "<select name=\"".$select_name."\">\n";
$curr_val = (isset($_REQUEST[$select_name])) ? $_REQUEST[$select_name] : $curr_val;
$mydir .= ($curr_val == "") ? " <option value=\"\" selected>...\n" : "<option value=\"\">...\n";
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
sort($files);
foreach ($files as $val) {
if (is_file($dir.$val)) { // show only real files (ver. 1.01)
$mydir .= " <option value=\"".$val."\"";
$mydir .= ($val == $curr_val) ? " selected>" : ">";
$mydir .= (strlen($val) > $char_length) ? substr($val, 0, $char_length)."...\n" : $val."\n";
$teller++;
}
}
$mydir .= "</select>";
}
if ($teller == 0) {
$mydir = "No files!";
} else {
return $mydir;
}
}
// example: echo select_files("path_to_your_folder", "label_name", "select_name", $current_value, $char_length);
?>
sample output:
<select name="file_in_folder">
<option value="" selected>...
<option value="AlienDa0.gif">AlienDa0.gif
<option value="INSTALL.pdf">INSTALL.pdf
<option value="active.bmp">active.bmp
<option value="edit.png">edit.png
<option value="eliksir.gif">eliksir.gif
<option value="hilite.gif">hilite.gif
<option value="logo.gif">logo.gif
<option value="logo.png">logo.png
<option value="paste.gif">paste.gif
<option value="sukka.png">sukka.png
<option value="teste.bmp">teste.bmp
<option value="visited.gif">visited.gif
</select>
<option value="" selected>...
<option value="AlienDa0.gif">AlienDa0.gif
<option value="INSTALL.pdf">INSTALL.pdf
<option value="active.bmp">active.bmp
<option value="edit.png">edit.png
<option value="eliksir.gif">eliksir.gif
<option value="hilite.gif">hilite.gif
<option value="logo.gif">logo.gif
<option value="logo.png">logo.png
<option value="paste.gif">paste.gif
<option value="sukka.png">sukka.png
<option value="teste.bmp">teste.bmp
<option value="visited.gif">visited.gif
</select>
notes:
editor - updated example string to include all arguments. Nice function olaf!



