Saturday, 18 August 2012

php list all directories and its files and subdirectory

Often you may need to list all the directories and subdirectory/files in tree structure in your side panel as the content or examples. This kind of things are mainly required in Educational or Learning blogs.

By looking those required here I have created one side panel which will help you to create yours one and also i have given full code explanation for creating / listing all the directories and its files. See code and its output as listed  below.

It it also very helpful to display all the image files of some directory without typing code for all Images. If you use following code then you can simply place the images in to your folder and you have done. Means all the image files will be loaded itself with php code. 

It will give you freedom to change your files/images at anytime without worrying about linking it to pages.



FILE NAME : index.php

<html>
<head>
           <title>Untitled Document</title>
           <link href="styles.css" rel="stylesheet" />

            <script type="text/javascript">
                        /* To show code into iframe set source of that file in iframe*/
                        function loadContent(x)
                        {
                                    document.getElementById('frmContent').src = x;
                         }
            </script>
</head>

<body>
<div id="body">
    <div id="header">
        <h1>Mukund </h1>
        <hr style="border:#A63600 3px solid"/>
    </div>

    <div id="container">
      <div id="sidebarLeft">
        <ul>
<?php
// set handle for directory resource
// '../' replace it with your desire directory.
        if ($handle = opendir('../')) {
// black list files which you dont wanna include. 
// you can add more files in following manner.
            $blacklist = array('.', '..', 'youDirectory');
        
          while (false !== ($file = readdir($handle)))
         {
                if (!in_array($file, $blacklist)) {
                    echo '<li>'.$file.'</li>';

                    // Set Directory path with latest directory here i have given path from root directory
                  $directory = "../".$file."/";

    // list each file of Directory - $file
    echo '<ul>';
         // for HTML files
$htmlFiles = glob($directory . "*.html" );
foreach($htmlFiles as $htmlFile)
{
echo '<li>
                                  <a href="#" onclick="loadContent(\''.$htmlFile.'\')">'.basename($htmlFile).'</a>
                                 </li>';
}

// Simillarly For PHP Files
$phpFiles = glob($directory . "*.php" );
foreach($phpFiles as $phpFile)
{
echo '<li>
                                  <a href="#" onclick="loadContent(\''.$phpFile.'\')">'.basename($phpFile).'</a>
                                 </li>';
}
           echo '</ul>';
/ / End of file listing.
             }
           }
          // close the directory handle.
            closedir($handle);
       }
       ?>
        </ul>           
    </div>
    <div id="content">
        <p>Hi, Click on respective pages to view content of it.</p>
        <iframe src="" id="frmContent"></iframe>
    </div>
    </div>
</div>
</body>
</html>


STYLESHEET : styles.css

body{
width:994px;
margin:0 auto;
font-family:Verdana, Geneva, sans-serif;
font-size:14px;
}
#body{
background:#DAEBFC;
}
#header{
padding:15px;
height:60px
}
#container{
padding:15px;
overflow:auto
}
#sidebarLeft{
float:left;
width:160px;
border:1px solid #CCC;
padding:5px;
font-size:12px
}
#sidebarLeft ul{
padding:0;
margin:0
}
#sidebarLeft ul li{
padding:5px;
list-style:none;
font-weight:bold;
font-size:16px
}
#sidebarLeft ul ul{
margin-left:15px
}
#sidebarLeft ul ul li{
font-weight:normal;
font-size:12px;
padding:2px
}
#content{
float:left;
padding:0 0 15px 15px;
width:775px
}
#content iframe{
width:770px;
height:720px;
margin:o auto;
overflow:scroll;
border:1px solid #ccc
}


Out put in IE9



Explanation of Code

Functions: 
opendir(): The opendir() function opens a directory handle to be used by the closedir(),    readdir(), and rewinddir() functions.This function returns a directory stream on success and FALSE and an error on failure. You can hide the error output by adding an '@' in front of the function name. 
readdir(): The readdir() function returns an entry from a directory handle opened by opendir().
This function returns a filename on success and FALSE on failure. The entries are returned in the order in which they are stored by the filesystem.
glob(): The glob() function returns an array of filenames or directories matching a specified pattern.This function returns an array of files/directories, or FALSE on failure.
Code Explanation

In above PHP code First you are creating a handle for your directory which is given as directory('../'). For current directory replace '../' to './'. Now create blacklist array which you don't want to display.

While loop will executed for times until it will false the readdir handle. In While loop return value of readdir() is checked. Here we are checking return value is identical and of same type too. If any directory entry whose name evaluates to FALSE will stop the loop.

Next, If loop will check for blacklist files directory if any files/directory that falls into blacklist it will be skipped. in_array($file, $blacklist) function is used to check that $file is in the $blacklist array or not.

Now, simply use the glob function to list all the matching files. glob($directory.'*.jpg') which will list all the files whose extension is .jpg. In above example I have used listed .php and .html files. For your specific files you can replace extension as per your requirement.

Last close the handle and terminate the code.