Open a directory
This simple function generates a select form element for all files of a given directory. The function is modified to work with “register_globals = off “. We can use the modified function in forms to update dynamic image names in a database table.
<?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”);
?>
