user4061223
user4061223

Reputation:

How to echo images and files within a directory onto a page php

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
            echo "<p>$entry\n</p>";
        } 


    }

    closedir($handle);
}

Above is the PHP code I am using to echo all the files in a directory. It works fine but the page echoes out this:

example.html

test.php

image.png

mobile.html

text.txt

image2.jpg


How do I make it so that if a file in the directory is an image, that gets shown as an image rather than text. E.g, the page will echo out:


example.html

test.php


(source: treehugger.com)

mobile.html

text.txt


In short, the code that I am currently using only displays the name of each of the files in the directory. I would like it to display the name of each of the files in the directory but however, if there is an image in the directory, instead of echoing the file name of the image, it instead displays the image.

Upvotes: 0

Views: 314

Answers (2)

Rizier123
Rizier123

Reputation: 59681

This should work for you if you only want to get images:

<?php

    foreach(glob("*.{jpg,png,gif,jpeg}", GLOB_BRACE) as $image)
        echo "<img src='" . $image . "' />";

?>

(Note no spaces in between the file extensions otherwise it's not going to work)

If you want all files just use this:

foreach(glob("*.*") as $file) {

    if(in_array(pathinfo($file, PATHINFO_EXTENSION), array("jpg", "png", "jpeg", "gif")))
        echo "<img src='" . $file . "' />";
    else
        echo $file . "<br />";
}

For more information about glob() see the manual: http://php.net/manual/en/function.glob.php

Upvotes: 1

Stefan Cvetkovic
Stefan Cvetkovic

Reputation: 144

Try this one:

if ($handle = opendir('.')) {

    $valid_image = array("jpg", "jpeg", "png", "gif");

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {

            $exploded = explode('.', $entry);

            if(in_array(end($exploded), $valid_image))
            {
                 echo '<img src="'.$entry.'">';
            }
            else
            {
                echo "<p>$entry\n</p>";
            }
        } 
    }
    closedir($handle);
}

Take care to post valid image path like:

echo '<img src="http://example.com/images/'.$entry.'">';

Upvotes: 0

Related Questions