How to list a directory in PHP and only show ZIP files

web-find-iconI wanted to list a directory in PHP. At the same time, I wanted to make sure only files are listed – not subdirectories or dot directories.

More specifically, I only wanted to include files with the ending .zip.

Two tools come to the rescue here:

  • scandir() to list the directory and give us an array
  • and the super handy pathinfo() to check a file extension

Here’s how I did it

function list_zipfiles($mydirectory) {
	
	// directory we want to scan
	$dircontents = scandir($mydirectory);
	
	// list the contents
	echo '<ul>';
	foreach ($dircontents as $file) {
		$extension = pathinfo($file, PATHINFO_EXTENSION);
		if ($extension == 'zip') {
			echo "<li>$file </li>";
		}
	}
	echo '</ul>';
}

Call the function with the directory of your choice – give it a full path like /var/your/directory. Next scandir() creates an array of files and directories which we iterate over with a foreach loop. I’m also formatting the output as an unordered list, hence the presence of some HTML elements in the echo statements.

The first thing we’ll do in the loop is to have a look at each file’s extension. If it is in fact “zip” then we’d like to list it. Other elements won’t show up.

I hope it helps 😉





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.