tim
tim

Reputation: 3913

make PHP run file when viewing any folder

I know this must be something around .htaccess or php.ini.

If a site visitor views ANY folder I want to automatically run a script listing the files in it (file_read.php).

But I only want the file_read.php to be in my root folder.

Can someone point me please?

Thanks.

Upvotes: 1

Views: 314

Answers (4)

dev-null-dweller
dev-null-dweller

Reputation: 29492

Not so long ago I had similar problem and ended with .htaccess like this:

<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>

Some explanation why like this:

  1. RewriteCond %{REQUEST_FILENAME} -d - to make it work only on directories
  2. RewriteCond %{REQUEST_FILENAME}index.php !-f - do not list directories containiing index file
  3. RewriteRule (.*/) file_read.php?dirpath=/$1 - note the ending slash, without it entering http://server.com/directory (no trailing slash) was redirected to something like http://server.com/directory/file_read.php?dirpath=directory, not exactly what we wanted.
  4. RewriteRule ^$ file_read.php?dirpath=/ - after adding trailing slash to rule above, directory lister stopped working for root directory (http://server.com/) so this line fixes it

Upvotes: 2

Peter
Peter

Reputation: 16943

.htaccess:

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

Upvotes: 7

imkingdavid
imkingdavid

Reputation: 1389

One way: Just remove any index file (e.g. index.php, index.html) and make sure you don't have a DirectoryIndex directive in .htaccess pointing to any existing file in the folder. Then when you view the folder, you will see all of the files in that folder. Of course, that doesn't use any read_file.php script to do it; it just lets the directory index itself.

Another way: As DaveRandom and Piotr Szymkowski showed, you can use .htaccess to route all calls to all directory to the read_file.php file, passing the current directory path as an argument to that file. Then, using readdir() (see the php manual for usage), you can list out the files within it.

Upvotes: 0

DaveRandom
DaveRandom

Reputation: 88697

RewriteEngine on
RewriteRule ^(.*)/$ file_read.php?dir=$1 [L]

Every request where the last character of the path is a / gets file_read.php, and the path requested will be available to file_read.php in $_GET['dir'].

Upvotes: 1

Related Questions