Creating a HTML selection list of file names matching a criteria, using PHP.

Published : 12.May.2007

I have been creating a specialised content management system for a client, and on one of the forms I needed to have a selection list of possible images for the logo.

So I needed a PHP function that would create a HTML selection list based on filenames from the images directory. However I didn't want to list all the images, only those which started with a particular filename expression; in effect doing a logo*.*

The function also had to be able to highlight the previous selected image, which would be suppiled from the database.

So I came up with the following cbo_recursedir function which takes three parameters; the directory to scan, the filename expression to look for, and the default filename as stored in the database. The function would be used like so :-

<?php

echo cbo_recursedir('d:/images/', 'logo', 'logo-web.jpg');

?>

The cbo_recursedir function

<?php

function cbo_recursedir($basedir, $findfiles, $value) {

$_content  = '';
$_content .= '<select name="cbofileselect" size="1"';

$hndl = opendir($basedir);
while($file = readdir($hndl)) {

    if ($file == '.' || $file == '..') continue;
        if (is_dir($file)) {
            /* if directory do nothing */
        } else {

        if(substr($file, 0, strlen($findfiles ))
            == $findfiles) {

            if($file == $value) {
                $_content .= '<option value="' . $file . 
                    '" SELECTED>' . $file . '</option>';
            } else {
                $_content .= '<option value="' . $file . 
                    '">' . $file . '</option>';
            }
        }
    }
}

$_content .= '</select>';

return $_content;

}

?>

What Next?

Bookmark this article at :-

 

About Author:
I'm a father, husband, and a software developer who works for the NHS. more »

Sections :
« Articles
« Contact


 

TIFF Splitter - A windows utility to split multipage TIFF files into single pages.