File Browser the Customized Way

Hello guys, its been a long time since I posted in this blog.

Today I am here to show you how to display your website directory contents like folders,images or even some files in a customized way.

See how GitHub is displaying our repository files and folders.

So, let’s get started.

What the default way looks like

The default way is what we see when we type any folder, that exists on a particular domain, is in the image below.

default-file-listing

But how our’s final one looks like is…

Custom-file-listing

What do we do here

Here we customize the URL parameters and identify the folders and files using PHP.

How to do it

  1. First we represent all folders with a “directory” image.

  2. Then we identify each file (text or any other) with a File icon.

The procedure for identifying the folders is…


<?php

function listDir($dir){

$files = array();

$links = array();

if(file_exists($dir)){

if(count(scandir($dir)) > 2){

$dh = scandir($dir);

foreach($dh as $folder){

if($folder != '.' && $folder != '..'){

if(is_dir($dir.'/'.$folder)){

$files[] = $folder;

$links[$folder] = "project.php?url=".$dir.'/'.$folder;

}else{

$files[] = $folder;

$links[$folder] = "project.php?url=".$dir.'/'.$folder;

}

}

}

}

return [$files,$links];

}else{

return "";

}

}

?>

This PHP code will return an array of files or sub-folders as an array to the callee of function.

Using this array of files, we can style our webpage to display how these values to be displayed.

My way of styling is as follows.


<?php

if(is_file($url)){

echo "<pre><code>".nl2br(htmlentities(file_get_contents($url)))."</code></pre>";

}else{

$file_links = listDir($url);
if(!empty($file_links)){
$files = $file_links[0];
$links = $file_links[1];
echo "<div class='files'>";
foreach($files as $f){
echo "<div>";
foreach($links as $key => $l){
if($f == $key){
if(is_dir($url.'/'.$key)){
echo "<span class='file-icon'><img src='directory.png'/></span>";
}else{
echo "<span class='file-icon'><img src='code.png'/></span>";
}
echo "<span class='file-name'>";
echo "<a href='".$l."'>".$key."</a>";
echo "</span>";
}
}
echo "</div>";
}
echo "</div>";
}

}

?>

Reading File contents

 

Live Demo     Download

Hope you guys enjoyed this.

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s