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

- by

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 '
    '; foreach ($dircontents as $file) { $extension = pathinfo($file, PATHINFO_EXTENSION); if ($extension == 'zip') { echo "
  • $file
  • "; } } echo '
'; }

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 πŸ˜‰

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.