Listing all files and directories using PHP

Spread the love

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:

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 !


Spread the love

Submit a Comment

Must be required * marked fields.


Related Articles

Mizanur Rahaman Mizan

7Zip Command Tutorial

Spread the love

Spread the loveTo Install 7Zip in the VPS or in your linux:

If the output

Spread the love
Read more:
Top 20 Wireframing and Mockup Tools for Developers Plus 9 bonus

I guess you already know, wireframing is the key to efficient UX development for mobile and web applications. Wireframing tools...

Better, Successful Life

When we stumble onto something and we are barefoot we might hurt our nails in such a way that it...