Create a list of items from a folder using scandir

David Carr

Tutorials PHP & MySQL

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.

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

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

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Fathom Analytics $10 discount on your first invoice using this link

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.