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

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 😉

About Jay Versluis

Jay is a medical miracle known as a Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Add your voice!