RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (5.84%*) • Fixed: 5.39% (5.84%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.19%*) • Investment PI: 5.49% (5.98%*)

Print all Files From and Below a Directory With PHP

This simple files will produce a list of all files below a particular directory, and provide a link to that particular file. The first function returns an array... and the second loops through the result and creates a list.

1
<?php 
2
/*
3
 Print all files from and below a directory with PHP
4
 http://www.beliefmedia.com/code/php-snippets/print-files
5
*/
6
 
7
function beliefmedia_list_directory_array($dir = '') {
8
 
9
  /* Start directory */
10
  if ($dir == '') $dir = '.';
11
 
12
  /* Name of this file */
13
  $filename = basename($_SERVER['SCRIPT_FILENAME']);
14
 
15
  /* If invalid directory */
16
  if (!is_dir($dir)) return false;
17
 
18
  $files = array();
19
 
20
    $fh = opendir($dir);
21
    while (($file = readdir($fh)) !== false) {
22
 
23
      /* Loop through files, skipping . and .. recursing if necessary */
24
      if (strcmp($file, '.') == 0 || strcmp($file, '..') == 0) continue;
25
 
26
      if ($file != "Thumb.db" && $file != "Thumbs.db" && $file != $filename) $filepath = $dir . '/' . $file;
27
      if (is_dir($filepath)) $files = array_merge($files, beliefmedia_list_directory_array($filepath));
28
        else array_push($files, $filepath);
29
 
30
    }
31
 
32
  /* Close directory handle */
33
  closedir($fh);
34
 
35
 return (array) $files;
36
}

The second function takes the resulting array and prints a list.

1
<?php 
2
/*
3
 Print all files from and below a directory with PHP
4
 Creates a basic list of all files from array
5
 http://www.beliefmedia.com/code/php-snippets/print-files
6
*/
7
 
8
function beliefmedia_list_directory($dir = '.') {
9
  $files = beliefmedia_list_directory_array($dir);
10
  foreach($files as $file) {
11
    echo '<a href="' . $file . '">' . $file . '</a>';
12
  }
13
}

Usage is as follows:

1
<?php 
2
/* Usage */
3
beliefmedia_list_directory('.');

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment