Php Tutorial: Getting All Files Within A Directory and Echoing In A Page

PHP Tutorials

29

Jan

This post will cover getting all of the files as an array and then echoing them in a web page. In this example we will be using it to populate a slider with all of the images within a website subdirectory ‘/images/’.

The first things you will need to have is your slider set up, and all of the images you will be using in the ‘/images/’ folder. For the purposes of this example, this will be the markup for the slider:

<div id=”slider”>

<div class=”slide”>
<img src=”images/image1.jpg”>
</div>

<div class=”slide”>
<img src=”images/image1.jpg”>
</div>

<div class=”slide”>
<img src=”images/image1.jpg”>
</div>

</div>

Once your slider markup is in place we will replace the “.slide” child div’s with a block of PHP.

<?php
foreach(glob(‘./images/*.*’) as $filename){
echo “<img src='” . $filename . “‘ />”;
}
?>

If you have the images in another directory, let’s say “slider” inside of “images, you would just have the code look like this:

<?php
foreach(glob(‘./images/slider/*.*’) as $filename){
echo “<img src='” . $filename . “‘ />”;
}
?>

If your directory is set up properly your page should then pull in all of the images in that folder dynamically.

PHP Tutorials

CALL US NOW