Listing Entire Directory With PHP

Hello, in this article, I will show you to list all the folders and files in the directory with php. I have prepared a code block for you below. If you run this in your own directory, you will see that all directory content has arrived :)

<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(function(){

    $('.hasFiles >div').on('click', function(){
        $(this).next('ul').toggle();
        $('.icon-down-dir', this).toggleClass('icon-up-dir');
    });

});
</script>
<style>
@import "font/fontello.css";
ul, li {
    list-style: none;
    margin: 0;
    padding: 0;
}
ul {
    -webkit-padding-start: 40px;
    padding-top: 10px;
}
ul li {
    padding-bottom: 10px;
}
ul li ul {
    display: none;
}
</style>
<?php

function filesize_formatted($path)
{
    $size = filesize($path);
    $units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $power = $size > 0 ? floor(log($size, 1024)) : 0;
    return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}

function listDirectory($dir){
    $directories = glob($dir);
    echo '<ul>';
    foreach ($directories as $file){

        echo '<li' . (is_dir($file) ? ' class="hasFiles"' : null) . '>';
        
        echo '<div>';

        if (is_dir($file)){
            echo '<i class="icon-folder"></i>';
        }

        if (is_file($file)){
            echo '<i class="icon-doc-inv"></i>';
        }

        $fileName = explode('/', $file);
        echo end($fileName);
 
        if (is_file($file)){
            echo ' <span>(' . filesize_formatted($file) . ')</span>';
        }

        if (is_dir($file)){
            echo '<i class="icon-down-dir"></i>';
        }

        echo '</div>';

        if (is_dir($file)){
            listDirectory($file . '/*');
        }

        echo '</li>';

    }
    echo '</ul>';
}

listDirectory('*');
Comments

There are no comments, make the firs comment