Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Create a list of items from a folder using scandir

David Carr

PHP & MySQL Tutorials

    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:

    //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.

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

    © 2009 - 2022 DC Blog. All code MIT license. All rights reserved.