Get all Images from a Directory Dynamically – PHP, jQuery Ajax
- Article
- Comment (2)
This tutorial will help you to get all images from a images directory dynamically. You can use simple php and jQuery functions to create custom images list . Here Not only images, you can get any list of items from a directroy. Here , first we have to get the path of our images directory
$img_dir = "path/to/images/directory/";
Now , we need to collect files from the directory by using php scandir function.
$images = scandir($img_dir);
Than, we have all the images in a single array namely $images. So we will get them one by one by using a simple “for” loop.
echo '<ul>' ; foreach($images as $img) { echo "<li> <img src=".$img_dir.$img." > </li> } echo '</ul>';
The above loop will bring all the files inside the $img_dir. We need to filter images only. The following code will help you to filter and get all images only.
//get_imgs.php $img_dir = "path/to/images/directory/"; $images = scandir($img_dir); $html = ''; $html .='<ul>'; foreach($images as $img) { if($img === '.' || $img === '..') {continue;} if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ) { $html .='<li> <img src="'.$img_dir.$img.'" ></li>' ; } else { continue; } } $html .='</ul>' ; echo $html ;
The php function to get all images in a directory. Now we need to get it on dynamically with the help of jQuery Ajax .here is the custom jquery function to display all images dynamically.
//jquery.custom.js jQuery('document').ready(function() { jQuery.ajax({ url: "get_imgs.php", type: "POST", dataType: "HTML", success: function( data ) { jQuery('body').append(data); }, error: function(jqXHR, data ) { alert ('Ajax request Failed.'); } }); });
Than as usual write your HTML code and when you open the html page, the images will be added automatically. If you need add some CSS Style to look and feel better.
<html> <head> <title> KV Codes Demo for adding Dynamic images from scanning a directory </title> <script src="jquery.min.js" > </script> <script src="jquery.custom.js" > </script> </head> <body> html content goes here. </body> </html>
Thats it now you can get all images from a directory dynamically, by using Jquery Ajax and PHP. In my next tutorial will help you to create image album with the help of pretty Photo.
Will this solution work on Mobile device browser also in a responsive manner.
Will work in mobile as well