简体   繁体   中英

Listing Directory files with php

I have a script which will list all the files from the image folder on the server into a drop down box.

$dir='images'; 

$list=scandir($dir);

if(isset($_POST['submit'])) echo 'Selected: ' . $_POST['image'];

    foreach($list as $file)
    {
        //ignore . (current dir) and .. (parent dir)
        if($file!=='.'&&$file!=='..')
        {
            echo "<option value=\"$file\"";
           if(isset($_POST['submit'])&&$_POST['image']==$file) echo 'selected="selected"';
            echo ">$file</option>";
        }
    }

What I am trying to do is when the file name of the image is selected that image is displayed.

 echo "<img src='images/". $file ."' />";

I tried using the file verable but it only seams to display the last image in the directory. How would I go about fixing this.

You will have to do this with Javascript. Once the php script loads it has no one of knowing what is happening in the users window. You will want to create an event listener to the onChange even of your option group. And when the selection changes you will want to replace the src of the image tag being used to show a preview.

I'd highly suggest using a JS Library such as Jquery or simliar to help with the event listening, and dom manipulation.

If you mean doing this on the form load, I'd say replace

if(isset($_POST['submit'])&&$_POST['image']==$file) echo 'selected="selected"';

with

if(isset($_POST['submit'])&&$_POST['image']==$file)
{
    echo 'selected="selected"';
    $selected_file = $file;
}

then this instead

echo "<img src='images/". $selected_file ."' />";

Because at the moment, it'll just load which ever one is last out of the foreach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM