简体   繁体   English

如何使用 php 链接和浏览子目录

[英]How to link and browse sub directories using php

I want to make a simple file browser using PHP.我想使用 PHP 制作一个简单的文件浏览器。 As I am new here in PHP.因为我是 PHP 的新手。 I need some push,我需要一些推动,

<table class="table">
  <thead>
    <tr>
      <th scope="col">Directory Name</th>
      <th scope="col">Last Modified</th>
      <th scope="col">Size</th>
    </tr>
  </thead>
  <tbody>
  <?php
        $folders= new DirectoryIterator(__DIR__);
        while($folders->valid()){

    ?>
    <tr>

      <td><?php echo "<a href='{$folders->current()}'>{$folders->current()}</a>" ?></td>
      <td></td>
      <td><?php echo $folders->getSize();?></td>
    </tr>

    <?php

        $folders->next();
    } ?>
  </tbody>
</table>

I have come to this so far.到目前为止,我已经做到了这一点。 How can I complete that code in order to have a functional file browser using php.我怎样才能完成该代码才能使用 php 获得功能性文件浏览器。 Thank you.谢谢你。

Here's a method to do that which also employs a level of security.这是一种方法,它也采用了一定程度的安全性。 While this may just be a school project or tutorial, you should always consider security.虽然这可能只是一个学校项目或教程,但您应该始终考虑安全性。 I have commented below but basically here is what's happening.我在下面发表了评论,但基本上这就是正在发生的事情。

You first set a $rootDirectory (which you will have to modify - this one is set to my filesystem).您首先设置一个$rootDirectory (您必须修改它 - 这个设置为我的文件系统)。 The rootDirectory is as far as you'll allow the browser to go - because as you see, the little .. link at the top of each folder/file list which allows for upward directory traversal and anyone could navigate themselves into stuff you don't want to ever expose. rootDirectory 只要您允许浏览器访问 go - 因为正如您所见,每个文件夹/文件列表顶部的小..链接允许向上目录遍历,任何人都可以将自己导航到您不知道的内容中不想暴露。

The links to the listed folders are modified to pass along the path to that folder FROM the root directory.列出的文件夹的链接被修改为从根目录传递到该文件夹的路径。 That way no one could fake a link to some inner OS folder.这样,没有人可以伪造指向某个内部操作系统文件夹的链接。 The links pass along this path in a GET variable ( ?dir=/some/path/ ).链接在GET变量 ( ?dir=/some/path/ ) 中沿此路径传递。 When the page loads, it looks for that GET variable, adds on the root directory to the beginning and puts it through a couple checks to make sure it's a real directory, that it isn't outside of our rootDirectory, etc. We do this by first converting it with realpath() .当页面加载时,它会查找那个GET变量,将根目录添加到开头,并对其进行几次检查以确保它是一个真实的目录,它不在我们的根目录之外,等等。我们这样做首先用realpath()转换它。 The incoming dir variable could be /myRootDirectory/../../../etc/mySecretConfigFile.conf which would pass our check because it has the root directory in it.传入的dir变量可能是/myRootDirectory/../../../etc/mySecretConfigFile.conf ,它会通过我们的检查,因为它包含根目录。 realpath() removes all those ../ so we can work with it. realpath()删除所有这些../以便我们可以使用它。

 <table class="table">
  <thead>
    <tr>
      <th scope="col">Directory Name</th>
      <th scope="col">Last Modified</th>
      <th scope="col">Size</th>
    </tr>
  </thead>
  <tbody>
  <?php
        // simple security - do not allow the file browser to get out of this root directory
        // SET THIS FOR YOUR SYSTEM
        $rootDirectory = '/Users/laphona/Sites/htdocs';

        // $dir = __DIR__ ;

        if ($_GET && $_GET['dir']) $dir = $rootDirectory . $_GET['dir'];
        else $dir = $rootDirectory;
        $dir = realpath($dir) ; // this takes out the ../ and the ./ and the .. that makes upward traversal possible despite our checks
       
        // if our root directory isn't present in the $dir
        if (strpos($dir, $rootDirectory) === false ) $dir = $rootDirectory ;
        // if our root directory isn't the very first part of the $dir
        if (strpos($dir, $rootDirectory) !== 0 ) $dir = $rootDirectory ;
        $folders= new DirectoryIterator($dir);
        while($folders->valid()){
            // set up the path here to be the direct path to the folder, minus our root directory
            $myPath = str_replace($rootDirectory, '', $folders->getPath()) . "/" . $folders->current();
            $myItem = "<a href='".$_SERVER['PHP_SELF']."?dir={$myPath}'>{$folders->current()}</a>" ;
            // if it's a file just present the name, no link
            if ($folders->isFile()) $myItem = $folders->current();
    ?>
    <tr>

      <td><?php echo $myItem ?></td>
      <td></td>
      <td><?php echo $folders->getSize();?></td>
    </tr>

    <?php

        $folders->next();
    } ?>
  </tbody>
</table>

Strict base path for security, folder navigation with back, file navigation with file content view.严格的安全基本路径、带返回的文件夹导航、带文件内容视图的文件导航。 DIV layout, no JavaScript and simple PHP. DIV 布局,没有 JavaScript 和简单的 PHP。

<?php
$Script = basename(__FILE__);
$RootPath = "F:\Web";
$FileHTML = [];

$Path = realpath("" . (isset($_GET["Path"]) ? $_GET["Path"] : $RootPath) . "" . (isset($_GET["Folder"]) ? "/{$_GET["Folder"]}" : null));
if(substr($Path, 0, strlen($RootPath)) !== $RootPath)$Path = $RootPath;

foreach(scandir($Path) as $Item)if($Item != "." && ($Path != $RootPath || $Item != "..")){
    $ItemWithPath = "{$Path}/{$Item}";

    if(is_dir($ItemWithPath)){
        $FolderHTML[] = "<div class=\"Item\"><a href=\"./{$Script}?Path={$Path}&Folder={$Item}\" class=\"Link\">{$Item}</a></div>";
    }
    else{
        //$FileHTML[] = "<div class=\"Item\"><a href=\"./{$Script}?Path={$Path}&Folder=.&{$Item}&File={$Item}\" class=\"Link\">{$Item}</a><span class=\"Size\">" . round(filesize($ItemWithPath) / 1024, 0) . " KB</span><span class=\"ModificationTime\">" . date("Y-m-d H:i:s", filemtime($ItemWithPath)) . " KB</span></div>";
        $FileHTML[] = "<tr class=\"Item\"><td><a href=\"./{$Script}?Path={$Path}&Folder=.&{$Item}&File={$Item}\" class=\"Link\">{$Item}</a></td><td class=\"Size\">" . round(filesize($ItemWithPath) / 1024, 0) . " KB</td><td class=\"ModificationTime\">" . date("Y-m-d H:i:s", filemtime($ItemWithPath)) . "</td></tr>";
    }
}
?><html>
    <head>
        <style>
            body{margin: 0; font-family: Verdana, Tahoma, Arial; font-size: 12px;}
            body:after{display: block; clear: both; content: '';}

            div{box-sizing: border-box;}

            .Navigation{float: left; width: 33%;}
            .Navigation > .CurrentPath{border: 1px Black solid; background: rgba(0, 255, 255, 0.25); padding: 5px;}
            .Navigation > .FolderList{height: calc(50% - 1em - 12px); border: 1px Grey solid; overflow-y: auto;}
            .Navigation > .FolderList > .Item{padding: 5px;}
            .Navigation > .FolderList > .Item:hover{background: rgba(255, 255, 0, 0.5);}
            .Navigation > .FolderList > .Item > .Link{text-decoration: none;}

            .Navigation > .FileList{height: 50%; border: 1px Grey solid; overflow-y: auto;}
            .Navigation > .FileList > table{font-size: inherit;}
            .Navigation > .FileList > table > tbody > .Item{}
            .Navigation > .FileList > table > tbody > .Item:hover{background: rgba(255, 255, 0, 0.5);}
            .Navigation > .FileList > table > tbody > .Item > td{padding: 5px;}
            .Navigation > .FileList > table > tbody > .Item > td > .Link{text-decoration: none;}
            .Navigation > .FileList > table > tbody > .Item > .Size{margin-left: 2em; white-space: nowrap;}
            .Navigation > .FileList > table > tbody > .Item > .ModificationTime{margin-left: 2em;}

            .FileContent{float: left; width: 67%;}
            .FileContent > .FileName{border: 1px Black solid; background: rgba(255, 0, 255, 0.25); padding: 5px;}
            .FileContent > .Content{height: calc(100% - 1em - 12px); background: Black; padding: 5px; color: White; white-space: pre;}
        </style>
    </head>
    <body>
        <div class="Navigation">
            <div class="CurrentPath"><?=$Path?></div>

            <div class="FolderList">
                <?=implode("\n  ", $FolderHTML) . "\n"?>
            </div>

            <div class="FileList">
                <table>
                    <tbody>
                        <?=implode("\n  ", $FileHTML) . "\n"?>
                    </tbody>                
                </table>
            </div>
        </div>

        <div class="FileContent">
            <div class="FileName"><?=isset($_GET["File"]) ? $_GET["File"] : null?></div>
            <div class="Content"><?=isset($_GET["File"]) ? file_get_contents("{$Path}/{$_GET["File"]}") : null?></div>
        </div>  
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM