I am trying to populate an HTML form’s drop down list with the contents of the current directory. I attempted to use PHP’s scandir() function to output these files as an array and then feed them into the option’s value tag within the HTML form.
I looked at various solutions available on SO and outside, but none seemed to work for me.
This is how my code looks like right now:
<form action="" >
<input type="submit" class="Links" value="Select Input">
<select >
<?php
$dir="./inputfiles/";
$filenames = scandir($dir);
foreach($filenames as $file){
echo '<option value="' . $filenames . '">' . $filenames . '</option>';
}
?>
</select>
</form>
For now I’m getting absolutely no options in the drop down menu.
I am very new to PHP and would appreciate your feedback as to how to make this work.
Further Changes:
I tried the solutions given below, and none seemed to work. I changed the code to check whether the PHP script is able to output any variable or not in the html forms list.
<form action="" >
<input type="submit" class="Links" value="Select Input">
<select >
<?php
$someval = "Video";
echo '<option value="value"> ' . $someval .' </option>';
?>
</select>
</form>
It displays ‘ . $someval .’ instead of Video in the menu bar
A couple of concerns with your script.
First, you need to output the correct variable within the options:
Second, you will likely need to add detection for
.and..in your loop, as you will likely not want to output them. You might also want to exclude directories as well.Third, you should probably make it clear exactly what directory you are trying to scan. Try using a full file path. If you need it relative to the currently executing file’s directory you can do something like:
Fourth, you might want to consider working with something like DirectoryIterator to give you some more convenient methods to do what you are looking to do (i.e. verifying it’s an actual file before listing it). So something like this:
In this trivial example, it you won’t necessarily gain a lot (in terms of saving extra code) by using DirectoryIterator, but I certainly like to point out it’s usage when I can, because if you needed to start doing things like showing file size, file permissions, file modification times, etc. It is much easier to do it using the DirectoryIterator class (or RecursiveDirectoryIterator class if you need to recursive) than using traditional PHP’s file system functions.