Create a list of items from a folder using scandir

David Carr

1 min read - 18th Jul, 2015

Quick tip to create a list page that will read the files from a directory and link to them is super easy. Using scandir to scan a folder then loop through the files and create a series of a links that link to the document. When scanning a directory hidden files like . and .. should be ignored using an array to store files to ignore:

<?php
//directory to look in
$directory = 'files';

//read all files from directory
$files = scandir($directory);    

//set ignore items
$ignore = array(".", "..");

//loop through the items stored in $files
foreach ($files as $doc) {

    //if item is not in the ignore array carry create an a link.
    if (!in_array($doc, $ignore)) {
        echo "<a href='$directory/$doc'>$doc</a><br>";
    }
}

withouth the extra spacing and comments this is a tiny snippet.

0 comments
Add a comment

Copyright © 2006 - 2024 DC Blog - All rights reserved.