PHP & MySQL | Tutorials

David Carr

Create a list of items from a folder using scandir

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.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

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