Dustin James
Dustin James

Reputation: 571

Adding uploaded files from a directory to a HTML <select> element using PHP

I'm trying to add uploaded files from a directory to a form element in HTML. I'm getting absolutely nothing when I run the page (not even the HTML). Here is the code:

<html>
<head>

</head>

<body>

<form name="adgen" id="adgen" method="post">

Choose a Banner Image:&nbsp;&nbsp;<select name="banimg">

<?php

//This variable specifies the file path for the banner image
$filepath="imgdir";

//This variable opens the directory for the correct file path for this select option
$openimg=opendir($filepath);

//This loops through the directory of files and if it finds a file it displays it as an option in the select form element
while($imgsel=readdir($openimg)){

    if($imgsel !=".." && $imgsel !="."){

        echo '<option value="'.$imgsel.'">'.$imgsel.'</option><br />');
        }

    }

closedir($openimg);
?>

</select>

</form>

</body>
</html>

Let me know if you can see what's hanging this up.

Upvotes: 0

Views: 261

Answers (3)

Kevin Vandenborne
Kevin Vandenborne

Reputation: 1387

2 Tips:

  1. Use a good IDE: http://netbeans.org/ or http://www.eclipse.org/. Both are good, both would have shown you a syntax error.

  2. Turn on errors when you are developing, turn them off when the site is live. Put this on top of the page: error_reporting(E_ALL);

The problem in your code was a simple (

<html>
<head>

</head>
<?php error_reporting(E_ALL); ?>
<body>

<form name="adgen" id="adgen" method="post">

Choose a Banner Image:&nbsp;&nbsp;<select name="banimg">

<?php

//This variable specifies the file path for the banner image
$filepath="imgdir";

//This variable opens the directory for the correct file path for this select option
$openimg=opendir($filepath);

//This loops through the directory of files and if it finds a file it displays it as an option in the select form element
while($imgsel=readdir($openimg)){
    if($imgsel !=".." && $imgsel !="."){
        echo '<option value="'.$imgsel.'">'.$imgsel.'</option><br />';
    }
}

closedir($openimg);
?>

</select>

Upvotes: 1

Vlad Volkov
Vlad Volkov

Reputation: 147

Try something like:

<?php
$dirContent = scandir('imgdir'); // don't forget to set full path to your folder
unset($dirContent[0]);
unset($dirContent[1]);
?>
<form name="adgen" id="adgen" method="post">
    Choose a Banner Image:
    <select name="banimg">
        <?php foreach ($dirContent as $image): ?>
            <option value="<?php echo $image?>"><?php echo $image ?></option>
        <?php endforeach; ?>
    </select>
</form>

Upvotes: 2

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22152

You have a syntax error here:

echo '<option value="'.$imgsel.'">'.$imgsel.'</option><br />');

Note the extra closed bracket at the end of the line. Anyway a good hint is to use error_reporting to debug and see what's the problem.

Upvotes: 1

Related Questions