Wednesday, October 15, 2014

Auto show all image inside a folder using php

This script automatically gets all image name inside a folder and show it in html file.
This is very usefull if we have so many image that we want to show. for example we want to show 500 images, instead of writing 500 lines of code we can get it in less than 20 lines of code.

Explanation :
First we need to know where our image folder is,
We put all the names inside an array then we use array_diff to remove ".." and "."
We will loop all the names inside the array and show it in html using img tag.
<ul>
<?php  
 $imgpath = 'img/'; // take note of the trailing slash
 //array_diff ,remove '..' and '.' so that it will not be included in our list
 $img = array_diff(scandir($imgpath), array('..', '.'));
 //Loop the array
 foreach($img as $imgs){ 
  ?>          
  <li>
   <div>
    <img src=<?php echo $imgpath .  $imgs;  ?>>
   </div>
  </li>           
  <?php  
 }
?>      
</ul>

Use subfolder and show the folder name
The first loop, We find first all the folders name.
The second loop finds the image name inside the first loop.
<ul>
<?php  
 $imgpath = 'img/'; // take note of the trailing slash 
 //array_diff ,remove '..' and '.' so that it will not be included on our list
 $folder = array_diff(scandir($imgpath), array('..', '.'));
 //Loop the array
 foreach($folder as $folders){ 
  //defined path + the folder name
  $imgfolder = $imgpath . $folders;  
  //scan all the content of the folder and gets the content inside it.
  $files2 = array_diff(scandir($imgfolder), array('..', '.'));
  foreach($files2 as $imgs){
  ?>          
  <li>
   <div>
    <?php echo substr($folders,0,25 );?></br>
    <img src=<?php echo $imgpath . $folders .'/'. $imgs;  ?>>
   </div>
  </li>           
  <?php 
  }
 }
?>      
</ul>

No comments:

Post a Comment