How to List Files in a Directory
I put this block of code together for some freelance work I’ve recently completed, where the client needed to be able to have dynamic control of content and assign these pieces of content to various files in the website. The easiest way to do this, especially for future expansion, was to use the following code to generate a list of all files in the directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // declare an array to hold the contents of our directory $arr_files = array(); // declare the full path to the directory we want the listings of $directory = '/home/sites/www.your-domain-name.com/httpdocs/'; // get a handle to this directory $handler = opendir($directory); // while we can still read from this directory, loop while ($file = readdir($handler)) { // as long as the current file isn't the current or parent directory if ($file != '.' && $file != '..') { // add the file to our array array_push($arr_files, $file); } // keep things tidy by closing the directory handle closedir($handler); |
In my work I expanded this code, so that the last 4 characters of each file had to be “.htm” to be added to the array as I only wanted to give the client the option of adding content to web pages, rather than any other file that may have been in the same directory.
Hope someone finds this useful!















