antiquarichat
antiquarichat

Reputation: 85

How to populate a drop down menu with file names from a directory as options using PHP?

I'm trying to create a drop down menu that points to a directory and populates a drop down menu with the names of certain files in that directory using PHP.

Here's what I'm working with:

<?php

$path = "pages/"; //change this if the script is in a different dir that the files you want
$show = array( '.php', '.html' ); //Type of files to show

$select = "<select name=\"content\" id=\"content\">";

$dh = @opendir( $path );

while( false !== ( $file = readdir( $dh ) ) ){
    $ext=substr($file,-4,4);
        if(in_array( $ext, $show )){       
            $select .= "<option value='$path/$file'>$file</option>\n";
    }
}  

$select .= "</select>";
closedir( $dh );

echo "$select";
?> 

This bit of code is giving me an errors, and I'm not even really attached to it if there's a better way of trying to accomplish what I'm trying to do.

Upvotes: 1

Views: 6761

Answers (3)

Baylor Rae&#39;
Baylor Rae&#39;

Reputation: 4010

It would be easier to use glob() because it can handle wildcards.

// match all files that have either .html or .php extension
$file_matcher = realpath(dirname(__FILE__)) . '/../pages/*.{php,html}';

foreach( glob($file_matcher, GLOB_BRACE) as $file ) {
  $file_name = basename($file);
  $select .= "<option value='$file'>$file_name</option>\n";
}

Upvotes: 2

parascus
parascus

Reputation: 1249

I don't know, which errors you get. But I think it won't work with the $show array because you're comparing the last 4 chars of the file with the contents of the array. Instead of $ext=substr($file,-4,4); you could write $ext=substr($file, strrpos( $file, ".")); which gives you the string from the position of the last occurance of ".".

Also I suggest for test reason that you omit the @ opening the directory because I think that the path cannot be found.

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71384

You need a full path reference (i.e. /var/www/pages/) instead of just "pages".

Also you might consider using DirectoryIterator object for easily getting to directroy information (if you are using PHP 5).

Upvotes: 1

Related Questions