Load Folder into PHP array


/ Published in: PHP
Save to your folder(s)

Loops through all files of a certain extension in the specified directory. Can be used to list all images in a given directory.


Copy this code and paste it in your HTML
  1. <?php
  2. $root = $_SERVER["DOCUMENT_ROOT"];
  3. $path = "/NCCDC/test/docs";
  4.  
  5. $allowed = array('jpg','gif','png'); /* file extension that you want to keep */
  6.  
  7. $iterator = new DirectoryIterator($root.$path);
  8. /* See php documentation on iterator */
  9. foreach ($iterator as $fileinfo) {
  10. if ($fileinfo->isFile()) {
  11. $path = $fileinfo->getPathname();
  12. $filename = $fileinfo->getFilename(); /*filename like 'picture1.jpg' */
  13. $info = pathinfo($filename);
  14. $ext = $info['extension']; /* extension like 'jpg' */
  15. $filename_noext = basename($filename,'.'.$ext);/*filename without extension like 'picture1' */
  16. /* Test to see if extension is allowed */
  17. if (in_array($ext, $allowed)){
  18. echo "<a href='$path'>$filename_noext</a><br/> \n";
  19. }
  20. }
  21. }
  22. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.