Mizanur Rahaman Mizan / February 5, 2016

Listing all files and directories using PHP

Have you ever wondered how without an index file all files and directories are appearing in your web root? Or in any directory. Well it is just a CGI script doing that on the server most of the cases. With PHP, you can simply do that. There are lots of way of doing so but today I will be showing the most simple way using a built-in function named glob().

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells. Manual to read: http://php.net/manual/en/function.glob.php

So here is the code that will show you how to do it:

Okay, breaking down the code into pieces for you.

$directory variable is to find out the files and directory on that directory. You can give any server based path here. I put it empty to show all files and folder of current directory of the PHP  script that is running this piece of code.

$local variable is getting the output of the glob function. In the glob function you will see I have appended “*” which means show all files and folders. If you want to find any specific file with certain extension you have to put the code just as below.

This particular code will only show files with a .php extension. Execute at your own risk buddies 🙂

Now if you want more than one extension then you can use the second parameter. Let me show you:

Here we have put the extension in curly braces and used a FLAG named Glob Brace

It actually shows the file extension from the braces. The final foreach() in all example code above is actually printing the file and directory name one by one. I have just made a link to them with an <a> tag!

So, that’s it. So simple isn’t it? You may have lots of other method which will tear your head’s neuron apart. But this simple tricks can help you a lot to show files and folder in a directory. Hope you have enjoyed. Comment below if you had any problem or you have something new to share about. I would love to hear from you !

 

FILED UNDER : Programming , Scrpitng

Submit a Comment

Must be required * marked fields.

:*
:*

Mizanur Rahaman Mizan

Life-long student of technology, a teacher , a tourist & a foodie.

Get me @: My Page | FB Profile | Twitter

For special content , subscribe!

Subscribe to our mailing list

* indicates required
Read more:
7Zip Command Tutorial

To Install 7Zip in the VPS or in your linux: [crayon-5b2af5359a2bd200854361/] If the output pointed that p7zip is already installed in...

The Debate between www vs non-www version WordPress website SEO setup

  A common question hits many of our minds often –why we use www in site URLs? What is the...

Close