PHP: Listing files in particular directory, a real world example

6 Mar

We are preparing our static files specially java script, css and images files to be moved to Amazon CDN. The thing we need to make sure here is that only those files that are in use should be moved. I was given a task to list all the js, css and images we are currently using in our application.

Initially I opened notepad and start writing down the names of those files.

Hehe, we don’t think out of the box.

The whole process was disgusting and I was feeling tired.

However working for a bit of time, an idea come to my mind, why not use computer to do the task for me.

And this is what I did.

Create .php file and write the following code in that file.

<form action=”” method=”post”>

<input type=”text” name=”path” />


<input type=”submit” value=”Submit” />



$pathName = $_POST[‘path’];


$dir = new DirectoryIterator($pathName);

foreach($dir as $fileInfo) {

if($fileInfo->isDot()) {

// do nothing

} else {

echo $fileInfo->__toString().'<br>’;





The code above did everything for me. Created a list of files in particular directory. I took print out of that list and crossed (x) files under construction.

In the first few lines I am creating form, adding input box for the directory path to be entered and submit button.

In the php code

  1. I get the path
  2. If path is not empty, I create an instance of DirectoryIterator available in PHP5, giving it directory path entered via input box.

3.Loop the $dir object and echo the result as string.


One Response to “PHP: Listing files in particular directory, a real world example”

  1. David March 10, 2009 at 12:22 pm #

    If a class implements __toString() you can just echo $object;

    Great blog here, with *lots* of resources, especially on Zend_Form and other Zend components.

    You should really look into a syntax highlighter for your blog, and aligning your code properly for much easier reading of the examples. That would make me want to come back, for sure.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: