How to display images from a directory in PHP

In this tutorial, we will go through the basics of how to display images from a folder in PHP. This will be done by going over some code that you can use to do so.

Sometimes displaying images directly from a directory is easier than displaying images from a database. If you want to learn how to display image files directly from a folder, please check out the steps below.

CONTENTS

How to get images from a directory and display them?

Here we have a directory called images and we want to show all the images from it on our website. So here is the code below:

<?php

	//get current directory
	$working_dir = getcwd();
	
	//get image directory
	$img_dir = $working_dir . "/images/";
	
	//change current directory to image directory
	chdir($img_dir);
	
	//using glob() function get images 
	$files = glob("*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}", GLOB_BRACE );
	
	//again change the directory to working directory
	chdir($working_dir);

	//iterate over image files
	foreach ($files as $file) {
	?>
		<img src="<?php echo "images/" . $file ?>" style="height: 200px; width: 200px;"/>
	<?php }
?>

Output:

How to get images from folder and display it?

The PHP function glob() is used to retrieve a list of files or directories matching a specified pattern. 

In the above code, I am using a pattern *.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}. This is because it is often seen that the image extension is sometimes in uppercase or in lowercase. So we have used extensions in our pattern here in lowercase and uppercase.

Here I am using getcwd() function to get the current directory in PHP. The chdir function will change the working directory to the image directory.

How to get all images from a folder and show the image with the name in a table?

Sometimes, you want to get all images (and maybe other files) from a folder. After that, you would like to show the images with names in a table. So here is the below code.

<?php

	//get current directory
	$working_dir = getcwd();
	
	//get image directory
	$img_dir = $working_dir . "/images/";
	
	//change current directory to image directory
	chdir($img_dir);
	
	//using glob() function get images 
	$files = glob("*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}", GLOB_BRACE );
	
	
	//again change the directory to working directory
	chdir($working_dir);
	?>
	<table width="100%" border="1px">
		<tr>
			<th>S/N</th>
			<th>Image Preview</th>
			<th>Image Name</th>
		</tr>
	
	<?php
	$c = 1;
	//iterate over image files
	foreach ($files as $file) {
	?>
		<tr align="center">
			<td><?php echo $c;?></td>
			<td><img src="<?php echo "images/" . $file ?>" style="height: 100px; width: 100px;"/></td>
			<td><?php echo $file ?></td>
		</tr>
	<?php $c++; } ?>
	</table>

Output:

How to get all images from folder and show the image with name in a table?

Display Random images from a folder

This is a basic “how-to” article about randomizing images from a folder in PHP. Some sites need this functionality because they have many kinds of images and numerous categories which makes it hard for them to manage their images; therefore, they need to randomly list the photos on the site.

PHP’s shuffle() function randomly reorders the elements of an array in order to give a random set. As the API documentation says, it is simply “a good way to generate a random permutation given an existing permutation.”

<?php

	//get current directory
	$working_dir = getcwd();
	
	//get image directory
	$img_dir = $working_dir . "/images/";
	
	//change current directory to image directory
	chdir($img_dir);
	
	//using glob() function get images 
	$files = glob("*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}", GLOB_BRACE );
	
	//shuffle the array element
	shuffle($files);
	
	//again change the directory to working directory
	chdir($working_dir);
	
	//iterate over image files
	foreach ($files as $file) {
	?>
		<img src="<?php echo "images/" . $file ?>" style="height: 100px; width: 100px;"/>
	<?php } ?>
	

	

Output:

Display Random image from folder

List all images files in directory and subdirectories

Why would you want to do this? One possible use case is that you’ve got an image gallery website with a very large number of images. You need to back up the site contents, including all the images, but don’t want to download millions of files or set up a database from which you can export thumbnails and then re-upload those again.

In order for this possible solution to work, your server must be able to run PHP. In addition, you should have write access to the folder containing folders containing the photos themselves (i.e., full permissions).

So, let’s get started. We begin our list of tasks by looping through all images from subfolders recursively in the given directory:

<?php
 
//get all images from directory and sub directory
function getImg($pattern, $flags = 0) {
    $files = glob($pattern, $flags); 
    
	foreach( glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir ) {
        $files = array_merge($files, getImg($dir.'/'.basename($pattern), $flags));
    }
    return $files;
}

//to find the all images
$result = getImg('*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
var_dump($result);

?>

Output:

List all images in folder and subfolders

Conclusion:

In this blog post, we’ve covered the basics of how to display images from a folder in PHP. You should now be armed with enough information for you to get started on your own project without too much struggle. If there are any questions that come up while you’re working through this tutorial, feel free to contact us or comment below.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

5 thoughts on “How to display images from a directory in PHP”

  1. Hello! I’m a beginner programmer in need of some help with my current project, can you give some tips or advices? I need to access a list of folders and subfolders in a database and show the images when the client clicks in every subfolder, until now i only find tutorials about listing a directory or a list of archives but nothing about showing a list of folders which the client could navigate

    Thanks in advance!

    Reply
  2. Hi could u tell me if my video chat call on whatsapp with my husband is getting recorded either by him or he has a group chat whilst we are speaking Nd and they Are recording me as I hear my own voice and other people s to and strangers noise
    On my whatsapp video call and its only when I call him it happens

    Reply
  3. Hi

    Where is the Windows path of the image directory? Should it be in localhost? I need to integrate data in mysql and images from an external harddrive in a webpage for editing the database.

    As first step I am trying to display the images in the external harddrive similar to the one you have done. How do I do this?

    Reply

Leave a Comment