使PHP运行文件时,查看任何文件夹


make PHP run file when viewing any folder

我知道这一定是。htaccess或php.ini之类的东西。

如果一个站点访问者查看任何文件夹,我想自动运行一个脚本,列出其中的文件(file_read.php)。

但我只希望file_read.php在我的根文件夹

谁能给我指一下?

谢谢。

.htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*) file_read.php?dirpath=$1

不久以前我有过类似的问题,并以.htaccess结尾,像这样:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}index.php !-f
RewriteCond %{REQUEST_FILENAME}index.html !-f
RewriteRule (.*/) file_read.php?dirpath=/$1 [L]
RewriteRule ^$ file_read.php?dirpath=/ [L]
</IfModule>

一些解释为什么像这样:

  1. RewriteCond %{REQUEST_FILENAME} -d -使其仅在
  2. 目录下工作
  3. RewriteCond %{REQUEST_FILENAME}index.php !-f -不列出包含索引文件
  4. 的目录
  5. RewriteRule (.*/) file_read.php?dirpath=/$1 -注意结束斜杠,没有它进入http://server.com/directory(没有尾斜杠)被重定向到类似http://server.com/directory/file_read.php?dirpath=directory的东西,不完全是我们想要的。
  6. RewriteRule ^$ file_read.php?dirpath=/ -在上面的规则中添加斜杠后,目录列表不再为根目录(http://server.com/)工作,所以这行修复了它
RewriteEngine on
RewriteRule ^(.*)/$ file_read.php?dir=$1 [L]

每个路径的最后一个字符是/的请求获得file_read.php,并且所请求的路径将在$_GET['dir']中提供给file_read.php

一种方法:只需删除任何索引文件(例如index.php, index.html),并确保在.htaccess中没有指向文件夹中任何现有文件的DirectoryIndex指令。然后,当您查看文件夹时,您将看到该文件夹中的所有文件。当然,这并不需要使用任何read_file.php脚本;它只是让目录自己索引。

另一种方式:正如DaveRandom和Piotr Szymkowski所展示的,您可以使用.htaccess将对所有目录的所有调用路由到read_file.php文件,将当前目录路径作为该文件的参数传递。然后,使用readdir()(请参阅php手册中的用法),您可以列出其中的文件。