Creating a HTML selection list of file names matching a criteria.

© copyright 12.May.2007 by Paul Bradley filed under PHP


[Ad] need a break from coding?

Hoseasons Villas

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;

}

?>

 


If you have found this article helpful or useful please consider linking to it, emailing it to friends, or share it with others using social sites like del.icio.us, Stumble Upon or Twitter.

Paul Bradley

About the Author
Paul Bradley is a VB.NET software developer living and working in Cumbria. He has over 20 years programming experience. He also produces e-learning videos at Code by Example and Linux by Example

Other Popular Articles

Categories & Topics

Home · Apache · JavaScript · Perl · PDF · PHP · MySQL · MSSQL · TAR · Ubuntu Linux · Video · Visual Basic

Browse the complete article history, and if you like what you see; consider subscribing to the rss feed.