Directory Listing with PHP file & dir functions

I always had a habit of managing everything in different folders, be it the documents, photographs, programs or projects. So when I started web development, everyday I use to endup creating something new in the new folder.
But then more the folders, more difficult to manage and remember whats in it although I use to make sure to give it a intutive name.

Then one day I decided to make my www folder more manageable or basically more identifiable. So I wrote a small program to display all the folders in an HTML file neatly.
And dropped a README file into the folder with very short description which would displayed along with the folder name on the HTML page.

Level: Beginner

Requirements: What we require here are very basic directory & file operations in PHP. We will learns them while on the way. Classes in PHP.

So lets get started!!

Step 1:

We are going to write few independent functions.

A. Function getFolders():

We are going to open the directory with opendir() function.
The we are going to read each and every file and folder from the opened directory with readdir() and if its directory we are going to make a list of it.
And in the end we are going to close the directory using the closedir() function.

<?php
function getFolders($dir) {
    $arrFolder = null;
    if ($handle = opendir($dir)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != ".." && is_dir($file) && strpos($file, '.') === false) {
                $arrFolder[] = $file;
            }
        }
        closedir($handle);
    }
    return $arrFolder;
}
echo '<pre>';
// we are providing '.' since it means the current directory.
print_r(getFolders('.'));
?>

This is how it will work. Click Here.

B. Function getReadMe():

This function will take the directory path as a parameter and then its going to check if README file exists under that folder by using the file_exists() function.
If the file exists then we are going to read the content of the file with file_get_content() function.
if the README file does not exists then we going to put a default message.

<?php
function getReadMe($dir) {
    $filepath = $dir . '/README';
    if (file_exists($filepath)) {
        return substr(file_get_contents($filepath), 0, 100);
    } else {
        return 'No README file found for this folder';
    }
}

echo getReadMe('testfolder1');
echo '<hr />';
echo getReadMe('testfolder2');
?>

This is how it will work. Click Here.

Step 2:

Now we are going to use the above written function to complete out program. We are going to write a simple class to achive this.
Final script would be like this – with little loops of arrays and HTML and CSS.

<?php

error_reporting(E_ALL);

class DirList {

    public $dirtoread = null;
    function __construct($dir) {
        $this->dirtoread = $dir;
    }

    function getFolders($dir) {
        $arrFolder = null;
        if ($handle = opendir($dir)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." && is_dir($file) && strpos($file, '.') === false) {
                    $arrFolder[] = $file;
                }
            }
            closedir($handle);
        }
        return $arrFolder;
    }

    function getReadMe($dir) {
        $filepath = $dir . '/README';
        if (file_exists($filepath)) {
            return substr(file_get_contents($filepath), 0, 100);
        } else {
            return 'No README file found for this folder';
        }
    }

    function printList() {
        $strHTML = '<ul>';

        $arrFolderList = $this->getFolders($this->dirtoread);

        if (!empty($arrFolderList) && is_array($arrFolderList)) {
            if (count($arrFolderList) > 0) {
                foreach ($arrFolderList as $directory) {
                    $strHTML .= '<li><h2><a href="' . $directory . '">' . $directory . '</a></h2><p>' . $this->getReadMe($directory) . '</p></li>';
                }
            } else {
                $strHTML .= '<li>no folder found</li>';
            }
        }
        $strHTML .= '</ul>';
        return $strHTML;
    }

}

$dir = new DirList('.');
echo '<!DOCTYPE html>
<html>
<head>
<title>List of demos</title>
<style>
body,ul,li,a,h2,p{padding:0;margin:0}
body{background:#EEE;font-family:Verdana, Ubuntu;}
ul{list-style:none;padding:15px;}
li{background:#aaa;display:block;float:left;width: 18%;margin: 10px;padding: 5px 10px;height:150px;}
h2{border-bottom:1px solid #DDD}
a{text-decoration:none;}
p{padding:15px 5px;}
</style>
</head>
<body>' . $dir->printList() . '</body>
</html>';
?>

This is the final step. Click Here.

Conclusion:

I hope you liked very simple but kind of effective PHP snippet. Will like if you got any suggestions or comments to make.

Learning Regular Expressions – Resource

Regular Expression is one the the powerful term in programming world. It has become the part of the daily programming world. Although it might be simple form validation in javascript or pattern matching while crawling the webpage and yes you can do it with Regular Expression.

Javascript, PHP, MySQL, Python…. list does not end…. regular expression is an in built part of it. And if not then surely it has some library to support it in some way or the other.

Those who know it, can create magic on the go, and those who don’t know it are afraid like hell. My suggestion go visit the hell and you will never regret a thing about it.

Following are the the few resource from the site www.webtechtuts.com

All Regular Expression articles on Webtechtuts.com
Regex Category on Webtechtuts.com

Regular Expression:

  1. Learn writing regular expression in 60 minutes
  2. Regex – Literal Characters And Special Characters
  3. Regex – How a Regex Engine Works Internally?
  4. Regex – Character Classes or Character Sets
  5. Regex – Dot Matches (Almost) Any Character
  6. Regex – Start and End of String or Line Anchors
  7. Regex – Word Boundries in Regular Expression
  8. Regex – Alternation
  9. Regex – Optional Item
  10. Regex – Repetition Using Various Quantifiers
  11. Regex – Matching Modes
  12. Regex – Free Spacing
  13. Regex – Adding Comments

All the best. Rule Regular Expression.

Javascript – Traversing the HTML DOM recursively

This post will give idea about HTML DOM Objects and way we can use its methods and attributes to navigate or traverse through it.

Introduction:
How to traverse the complete HTML BODY covering each HTML element recursively and forming a tree You need to be aware of very basic Javscript DOM methods. W3schools is the wonderful resource to learn this basics. Go through all the functions but what we need for this exercise is getElementById() and getElementsByTagName()

Eg: HTML

<html>
  <head>
    <title>
      Javascript - HTML Tree Parser
    </title>
  </head>
  <body>
    <div id="header">
      <h1>Javascript - HTML Tree Parser</h1>
    </div>
    <ul id="nav">
      <li><a href="one.html">one</a></li>
      <li><a href="two.html">two</a></li>
    </ul>
    <div id="footer">
    </div>
  </body>
</html>

Step I:
We are going to write a javascript function – lets call it htmlTree

<script type="text/javascript">
   function htmlTree(){}
</script>

Step II:
We will need to first get the body element, we can do it with the help of getElementsByTagName(‘body’), which will return you the body tag. But since the function itself is plural it will always return you an array even if it has only one single element. Since body is the present only once we will refer to the 0th element of an array.

<script type="text/javascript">
  function htmlTree(){
    var body = document.getElementsByTagName('body')[0];
  }
</script>

Step III:
Now we will check if the body tag has any children – we can do that by using hasChildNodes() method, if yes then we will first refer to the first child, we can do that with the attribute “firstChild”. Also we can get the name of the tag with an attribute “tagName”. After reading the first child we will go to the next child, with use of an attribute “nextSibling”

<script type="text/javascript">
  function htmlTree(){
    var body = document.getElementsByTagName('body')[0];
    if (body.hasChildNodes()) {
      var child = body.firstChild;
      alert(child.tagName); // as per the above HTML example it will alert "div"
      var next = child.nextSibling;
      alert(next.tagName); // as per the above HTML example it will alert "ul"
    }
  }
</script>

But this wont meet our purpose, we dont know the length of the tree and we also dont know how deep each branch is going to be, so we will make this function recursive to perform these similar step for eavery branch till it reaches it leaves. Step IV: We will print the name of the tag identified and check if it has children if yes then we will recursively call the function again which will print its name and check if it has child – it will happen till it reaches element with no child

<script type="text/javascript">
  function htmlTree(obj){
    var obj = obj || document.getElementsByTagName('body')[0];
    alert(obj.tagName);
    if (obj.hasChildNodes()) {
      var child = obj.firstChild;
      htmlTree(child);
    }
  }
</script>

When you execute this, you get first alert as BODY but very next alert as undefined – where in it should have been DIV. This is because between BODY and the DIV tag there is the white space which is considered to be an empty text – well we need to avoid such occurrences Step V: Go through nodeType on W3schools. Since here we are looking for an HTML elements, we will check for nodeType = 1. If it is 1 then we will recursively call the function if not we will move onto its sibling

<script type="text/javascript">
  function htmlTree(obj){
    var obj = obj || document.getElementsByTagName('body')[0];
    alert(obj.tagName);
    if (obj.hasChildNodes()) {
      var child = obj.firstChild;
      while(child){
        if (child.nodeType === 1) {
          htmlTree(child);
        }
        child = child.nextSibling;
      }
    }
  }
</script>

Step VI:
These alerts are quiet annoying, so lets make some subtle changes so that this function returns us complete tree. I personally like “ul li ul li” to represent a tree. Here is the modified function

<script type="text/javascript">
  function htmlTree(obj){
    var obj = obj || document.getElementsByTagName('body')[0];
    var str = "<ul><li>" + obj.tagName;
    if (obj.hasChildNodes()) {
      var child = obj.firstChild;
      while (child) {
        if (child.nodeType === 1) {
          str += htmlTree(child)
        }
        child = child.nextSibling;
      }
    }
    str += "</li></ul>";
    return str;
  }
  document.write(htmlTree());
</script>

Step VI:
Since at the very beginning we were talking about just HTML elements, we will get rid of all the javascript inside HTML. We can achieve that by simply adding a simple check in the condition where we check the nodeType.

// Change
if (child.nodeType === 1)
// to
if (child.nodeType === 1 &amp;&amp; child.nodeName != 'SCRIPT')

Demo:
Javascript – HTML Tree Parser