0

I am working on two things:

  • displaying directory list from my local drive and
  • displaying the contents of folder from that directory when clicked on folder name.

I am getting the directory list from the following code, but I am unable to get the path along with the file name which i want to display the contents by using those.

Here I am getting path from $path, which is inside createDir() and file name from queue array which is also in createDir() function.

Can anyone help me to get the whole path along with the filename in to a variable which I can use outside of the function for displaying contents?

Getting Directory list:

$path = "ggadmin/production/images/";

function createDir($path = '.')
{   
    if ($handle = opendir($path)) 
    {
        echo "<ul id='image'>";

        while (false !== ($file = readdir($handle))) 
        {
            $queue[]='';
            if (is_dir($path.$file) && $file != '.' && $file != '..')
                printSubDir($file, $path, $queue);
            elseif ($file != '.' && $file !='..')
                $queue[] = $file;
        }
        global $file;
        global $data;
        $file1 = implode(',',$queue);
        $file2 = explode(',', $file1);
        $data = var_export($path.$file1);
        /* eval('$data1 = ' . $data);*/

        printQueue($queue, $path);
        echo "</ul>";
    }
}

function printQueue($queue, $path)
{
    foreach ($queue as $file) 
    {
        printFile($file, $path);
    } 
}

function printFile($file, $path)
{
    echo  "<li><a href=\"".$path.$file."\">$file</a></li>";
}        

function printSubDir($dir, $path)
{       
    global $data1;
    echo "<li><a href=test1.php?data=$data1><span class=\"toggle\">$dir</span></a>";
    createDir($path.$dir."/");
    echo "</li>";

    /* global $image = createDir($path.$dir."/");*/
}

createDir($path);
global $path;
var_dump($path);
4
  • 1
    To get a path, you can do __DIR__ in PHP. Commented Aug 7, 2018 at 9:01
  • …removed JS tags since this question is about PHP only Commented Aug 7, 2018 at 9:08
  • 1
    I really don't understand the question. Commented Aug 7, 2018 at 9:09
  • I am getting the path value from function printSubDir($dir,$path) which i assigned to a variable $data (inside function) can any one tell me how to get and use variable $data in <img> tag which is outside of loop to display contents? Commented Aug 7, 2018 at 10:39

3 Answers 3

1

I wanna share my two solutions on the same task. 1) Styled solution

<?
header('Content-Type: text/html; charset=utf-8');
$host = $_SERVER['HTTP_HOST'];
setlocale(LC_TIME, "ru_RU.utf8");
date_default_timezone_set('Europe/Moscow');

/*
Directory Listing Script - Version 2
====================================
Script Author: Ash Young <[email protected]>. www.evoluted.net
Layout: Manny <[email protected]>. www.tenka.co.uk
*/
$startdir = '.';
$showthumbnails = false; 
$showdirs = true;
$forcedownloads = false;
$hide = array(
                'dlf',
                'public_html',              
                'index.php',
                'Thumbs',
                '.htaccess',
                '.htpasswd',
                'default.php'
            );
$displayindex = false;
$allowuploads = false;
$overwrite = false;

$indexfiles = array (
                'index.html',
                'index.htm',
                'default.htm',
                'default.html'
            );

$filetypes = array (
                'png' => 'jpg.gif',
                'jpeg' => 'jpg.gif',
                'bmp' => 'jpg.gif',
                'jpg' => 'jpg.gif', 
                'gif' => 'gif.gif',
                'zip' => 'archive.png',
                'rar' => 'archive.png',
                'exe' => 'exe.gif',
                'setup' => 'setup.gif',
                'txt' => 'text.png',
                'htm' => 'html.gif',
                'html' => 'html.gif',
                'php' => 'php.gif',             
                'fla' => 'fla.gif',
                'swf' => 'swf.gif',
                'xls' => 'xls.gif',
                'doc' => 'doc.gif',
                'sig' => 'sig.gif',
                'fh10' => 'fh10.gif',
                'pdf' => 'pdf.gif',
                'psd' => 'psd.gif',
                'rm' => 'real.gif',
                'mpg' => 'video.gif',
                'mpeg' => 'video.gif',
                'mov' => 'video2.gif',
                'avi' => 'video.gif',
                'eps' => 'eps.gif',
                'gz' => 'archive.png',
                'asc' => 'sig.gif',
            );

error_reporting(0);
if(!function_exists('imagecreatetruecolor')) $showthumbnails = false;
$leadon = $startdir;
if($leadon=='.') $leadon = '';
if((substr($leadon, -1, 1)!='/') && $leadon!='') $leadon = $leadon . '/';
$startdir = $leadon;

if($_GET['dir']) {
    // check this is okay.

    if(substr($_GET['dir'], -1, 1)!='/') {
        $_GET['dir'] = $_GET['dir'] . '/';
    }

    $dirok = true;
    $dirnames = split('/', $_GET['dir']);
    for($di=0; $di<sizeof($dirnames); $di++) {

        if($di<(sizeof($dirnames)-2)) {
            $dotdotdir = $dotdotdir . $dirnames[$di] . '/';
        }

        if($dirnames[$di] == '..') {
            $dirok = false;
        }
    }

    if(substr($_GET['dir'], 0, 1)=='/') {
        $dirok = false;
    }

    if($dirok) {
         $leadon = $leadon . $_GET['dir'];
    }
}



$opendir = $leadon;
if(!$leadon) $opendir = '.';
if(!file_exists($opendir)) {
    $opendir = '.';
    $leadon = $startdir;
}

clearstatcache();
if ($handle = opendir($opendir)) {
    while (false !== ($file = readdir($handle))) { 
        // first see if this file is required in the listing
        if ($file == "." || $file == "..")  continue;
        $discard = false;
        for($hi=0;$hi<sizeof($hide);$hi++) {
            if(strpos($file, $hide[$hi])!==false) {
                $discard = true;
            }
        }

        if($discard) continue;
        if (@filetype($leadon.$file) == "dir") {
            if(!$showdirs) continue;

            $n++;
            if($_GET['sort']=="date") {
                $key = @filemtime($leadon.$file) . ".$n";
            }
            else {
                $key = $n;
            }
            $dirs[$key] = $file . "/";
        }
        else {
            $n++;
            if($_GET['sort']=="date") {
                $key = @filemtime($leadon.$file) . ".$n";
            }
            elseif($_GET['sort']=="size") {
                $key = @filesize($leadon.$file) . ".$n";
            }
            else {
                $key = $n;
            }
            $files[$key] = $file;

            if($displayindex) {
                if(in_array(strtolower($file), $indexfiles)) {
                    header("Location: $file");
                    die();
                }
            }
        }
    }
    closedir($handle); 
}

// sort our files
if($_GET['sort']=="date") {
    @ksort($dirs, SORT_NUMERIC);
    @ksort($files, SORT_NUMERIC);
}
elseif($_GET['sort']=="size") {
    @natcasesort($dirs); 
    @ksort($files, SORT_NUMERIC);
}
else {
    @natcasesort($dirs); 
    @natcasesort($files);
}

// order correctly
if($_GET['order']=="desc" && $_GET['sort']!="size") {$dirs = @array_reverse($dirs);}
if($_GET['order']=="desc") {$files = @array_reverse($files);}
$dirs = @array_values($dirs); $files = @array_values($files);

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Welcome to My CV Folder.</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link href="http://www.main-hosting.com/hostinger/welcome/css/site.css" media="screen" rel="stylesheet" type="text/css" />
        <link rel="icon" type="image/png" href="http://cdx.kz/storage/app/media/logo_thumb32.jpg">
    </head>
    <body>
        <div id="main">
            <div id="content">
                <div class="header"></div>
                <div class="content">
                    <h1>Web Explorer</h1>
                    <p>NAVIGATION => <a href="http://wego.esy.es">HOME</a> <?
                    echo urldecode($_SERVER['REQUEST_URI']);                                        
                    ?></p>
                    <div id="files">
                        <div class="top"></div>
                        <div class="cont">

                            <div id="listingcontainer">
                                <div id="listing">
                                <?
                                $class = 'b';
                                if($dirok) {
                                ?>
                                  <div><a href="<?=$dotdotdir;?>" class="<?=$class;?>"><img src="http://www.main-hosting.com/hostinger/welcome/index/dirup.png" alt="Folder" /><strong>..</strong> <em>-</em><? $mtime = filemtime($dotdotdir); $mtime = date("m/d/Y H:i:s", $mtime); $mtime = strftime("%B %e, %G %T", strtotime($mtime)); print ucfirst($mtime); ?></a></div>
                                <?
                                    if($class=='b') $class='w';
                                    else $class = 'b';
                                }
                                $arsize = sizeof($dirs);
                                for($i=0;$i<$arsize;$i++) {
                                ?>
                                  <div><a href="<?=$leadon.$dirs[$i];?>" class="<?=$class;?>"><img src="http://www.main-hosting.com/hostinger/welcome/index/folder.png" alt="<?=$dirs[$i];?>" /><strong><?=$dirs[$i];?></strong> <em>-</em><? $mtime = filemtime($leadon.$dirs[$i]); $mtime = date("m/d/Y H:i:s", $mtime); $mtime = strftime("%B %e, %G %T", strtotime($mtime)); print ucfirst($mtime); ?></a></div>
                                <?
                                    if($class=='b') $class='w';
                                    else $class = 'b';  
                                }

                                $arsize = sizeof($files);
                                for($i=0;$i<$arsize;$i++) {
                                    $icon = 'unknown.png';
                                    $ext = strtolower(substr($files[$i], strrpos($files[$i], '.')+1));
                                    $supportedimages = array('gif', 'png', 'jpeg', 'jpg');
                                    $thumb = '';

                                    if($filetypes[$ext]) {
                                        $icon = $filetypes[$ext];
                                    }

                                    $filename = $files[$i];
                                    if(strlen($filename)>43) {
                                        $filename = substr($files[$i], 0, 40) . '...';
                                    }

                                    $fileurl = $leadon . $files[$i];
                                ?>
                                  <div><a href="<?=$fileurl;?>" class="<?=$class;?>"<?=$thumb2;?>><img src="http://cpanel.main-hosting.com/images/index/<?=$icon;?>" alt="<?=$files[$i];?>" /><strong><?=$filename;?></strong><em><?=round(filesize($leadon.$files[$i])/1024);?> KB</em><? $mtime = filemtime($leadon.$files[$i]); $mtime = date("m/d/Y H:i:s", $mtime); $mtime = strftime("%B %e, %G %T", strtotime($mtime)); print ucfirst($mtime); ?><?=$thumb;?></a></div>
                                <?
                                    if($class=='b') $class='w';
                                    else $class = 'b';  
                                }   
                                ?>
                                </div>
                            </div>

                        </div>
                        <div class="bottom"></div>
                        <div class="clear"></div>
                    </div>
                    <div class="clear"></div>
                </div>
                <div class="footer"></div>
                <div class="clear"></div>
            </div>
            <div id="footer">
                <div class="links">
                    <a href="http://cdx.kz" target="_blank">Also visit CDX.KZ</a> &copy; <? print date('Y'); ?>. 
                </div>

            </div>
        </div>
    </body>
</html>

2) Simple and functional solution

tml>
    <head>
        <meta charset="utf-8" />
        <title>File in current Folder</title>
    </head> 
    <body>
    <h1>File List</h1>
    <?
        $files = scandir('.');
        echo '<table>';
        foreach ($files as $key=>$file){
            echo '<tr>';
            if ($file=='index.php' or $file=='.'){}else{
                echo '<td><a href="'.$file.'">'.$file.'</a>';
                if ($file != '..')
                    echo '</td><td><a href="index.php?content='.substr($file,0,sizeof($file)-6).'">->Show file contents<-</a>';
                echo '</td>';
            }
            echo '</tr>';
        } 
        echo '</table>';
    ?>

    <?
        if (!empty($_GET['content'])){
            $file_name = str_replace('.','x',$_GET['content']).'.html';
            $content = file_get_contents($file_name);

            $content = htmlspecialchars($content);

            echo '<hr/>';
            echo 'File '.$file_name.' content:<br/>';
            echo '<pre><code>';
            echo $content;
            echo '</code></pre><hr/>';
        }
    ?>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, can you tell me how to refresh the particular <div> tag when clicked on the anchor tag? As i am trying that one as follows I am unable to pass the ur parameters which i defined with in a function.
<a href='#' id='btn_click'>$dir</a> JQuery: $(document).ready(function() { $('#btn_click').on('click', function() { var url = 'test1.php?data=$data'; $('#display').load(url + ' #display1'); }); });
Can we speak in Skype? I did not understand clearly what solution you want to get, but I think I'm able to help you. And then post here for others the solution we did.
Sorry i am unable to do that but i will explain you clearly here. As i am getting the list of directories on left side div tag and displaying their content on right side div tag(when clicked on folder name), while doing this process the whole page is loading each time when i clicked different folders. As i have huge amount of data the page loading time is more, so i want to reduce the page loading time by making only right side div reloading every time but not the whole page. I want to how to do this with my code as i am passing url with in a function. Can you suggest me the right way?
There are a lot of ways to do so. e.g. ReactJS+some backend. And a question: Do you want use a real folder tree, or some DB to emitate real folder tree?
|
0

Thanks, i sorted out my answer in the following way.

As my directory list is displaying properly with the above mentioned code. Rather than getting the parameters from two functions, I modified printSubDir($dir, $path) function as follows

function printSubDir($dir, $path)
    {       
        global $data;
        $data = $path.''.$dir;
                echo "<li><a href='test1.php?data=$data'><span 
 class=\"toggle\">$dir</span></a>";
        createDir($path.$dir."/");
        echo "</li>";
    }

From the above code i get ($_GET['data']) the data value in test1.php and displayed all contents test1.php itself.

Comments

0

I styled with bootstrap, look at this:

<html>
    <head>
        <meta charset="utf-8" />
        <title>Files and Folders</title>
        <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.1.2/cosmo/bootstrap.min.css" rel="stylesheet" integrity="sha384-bWCgyti3fD0r6vAulgU8WBFKOn7fne8sSrA5BVeNehYyqHOsyn7bBi7T848TkMo2" crossorigin="anonymous">
    </head> 
    <body>
    <div class="row">
        <div class="col-md-4">
            <h3>What is in folder?</h3>
            <?
                $files = scandir('.');
                echo '<table>';
                foreach ($files as $key=>$file){
                    echo '<tr>';
                    if ($file=='index.php' or $file=='.'){}else{
                        echo '<td><a href="'.$file.'">'.$file.'</a>';
                        if ($file != '..')
                            echo '</td><td><a href="index.php?content='.substr($file,0,sizeof($file)-6).'">->Show file contents<-</a>';
                        echo '</td>';
                    }
                    echo '</tr>';
                } 
                echo '</table>';
            ?>
        </div>

        <div class="col-md-8">
            <h2>File Content:</h2>
            <?
                if (!empty($_GET['content'])){
                    $file_name = str_replace('.','x',$_GET['content']).'.html';
                    $content = file_get_contents($file_name);

                    $content = htmlspecialchars($content);

                    echo '<hr/>';
                    echo 'File '.$file_name.' content:<br/>';
                    echo '<pre><code>';
                    echo $content;
                    echo '</code></pre><hr/>';
                }
            ?>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    </body>
</html>

1 Comment

The solution for real folder tree. just save this code as index.php in each folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.