简体   繁体   English

使用php浏览本地目录和文件

[英]Browsing local directories and files with php

Instead of the traditional navigation, I am trying to emulate the terminal navigation, or how you navigate with vim. 代替传统的导航,我尝试模拟终端导航,或者您如何使用vim导航。 Example: 例:

..
index
otherfile

This is my code: 这是我的代码:

$dir = realpath(dirname(__FILE__));
if(is_dir($dir)){
    if($open = opendir($dir)){
        while(($file = readdir($open)) !==false){
        if(is_dir($file)){
             if($file == '.'){ }
             else{
                echo "<a href=".$file.">".$file."</a><br/>";
            }
        } 
        else{       
        $name = explode('.php',$file);
        echo "<a href=".$file.">".$name[0]."</a><br/>";
        }
        }

    }
}
else{
    echo $dir." Was not found";
    }
 }
  1. How can I remove the file or folder I am in from the list? 如何从列表中删除我所在的文件或文件夹? For example, if I am on the page index.php, it is still appearing on the list. 例如,如果我在index.php页面上,它仍显示在列表中。

  2. I want to sort files by given them a number example '1file.php' '2anotherfile.php'.. How could I sort them by the number, then remove the number and '.php', and finally print it out? 我想通过给它们一个数字示例'1file.php''2anotherfile.php'来对文件进行排序。如何按数字对它们进行排序,然后删除数字和'.php',最后将其打印出来?

If you feel like refactoring something please do so... 如果您想重构某些东西,请这样做...

在此处输入图片说明

  1. "How can I remove the file or folder I am in from the list? For example, if I am on the page index.php, it is still appearing on the list." “如何从列表中删除我所在的文件或文件夹?例如,如果我在index.php页面上,它仍会出现在列表中。”

Just check if the current item is the current file, if it is then skip it: 只需检查当前项目是否为当前文件,如果是则跳过它:

else {
    if ($name == basename(dirname(__FILE__))) continue; // if this is the current file, go to the next iteration of the loop
    $name = explode('.php',$file);
    echo "<a href=".$file.">".$name[0]."</a><br/>";
}

Note that this assumes you are in the same directory as the file (which it can do because $dir is always the directory the script is in), if not you can just add a directory check as well. 请注意,这假定您与文件位于同一目录(之所以可以这样做,因为$dir始终是脚本所在的目录),否则,您也可以添加目录检查。

  1. "How can add a number to the start of the file or folder, example 1index.php, then on the code, organize all the files and folder by number, and print them without the number and '.php'?" “如何在文件或文件夹的开头添加数字,例如1index.php,然后在代码上,按数字组织所有文件和文件夹,并在没有数字和'.php'的情况下打印它们?”

Well I'm not too sure what you mean by this, but if you mean sort alphabetically, then it is already alphabetically sorted when you get the list. 好吧,我不太确定这是什么意思,但是如果您的意思是按字母顺序排序,那么当您获得列表时,它已经按字母顺序排序了。

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

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