Directory Listing with PHP file & dir functions

By Swapnil Sarwe, Published on 06 Jan, 2012

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.

© 2021 Tails - Tailwindcss Page Builder

Instagram Twitter GitHub