tags:

views:

52

answers:

2

When I link to a file in a directory, I want to open that file as a param in a php program.

For example, I have a directory temp, and files aa.txt, bb.txt, and test.php. When I link to aa.txt it should be handled like test.php?f=aa.txt.

What do I change in the .htaccess file?

the code in the test.php

<?php
$f=$_GET['f'];
if(@file_exists($f)){
    $inhoud = file_get_contents($f);
}else{
    $inhoud = "Not found\n";
}
print "hallo <hr>".$inhoud;

?>
+2  A: 

You want to use mod_rewrite, and define rules like the following within a .htaccess file in the directory you want it to apply to:

# Enable mod_rewrite
RewriteEngine on

# If the request is an actual file and not test.php...
RewriteCond %{REQUEST_FILENAME} !test.php$
RewriteCond %{REQUEST_FILENAME} -f

# ... then rewrite the URL to pass the filename as a parameter to test.php
RewriteRule /(.*)$ test.php?f=$1 [QSA]
Daniel Vandersluis
i tested and it shows the original content of the file (a.txt ) my script just puts hello in front of the result
Grumpy
Sounds like your test.php file isn't doing what you want it to do...
Daniel Vandersluis
i added the source of test.php
Grumpy
Looks like it's doing exactly what you told it to do. `file_get_contents` gets the content of a file and then you're echoing it. If you want to do something else with the file and can't figure out how to do so, you should create another question.
Daniel Vandersluis
it shows the original content of the aa.txt and if i remove the file aa.txt it doesnt show "not found" what am i doing wrong? (hallo doesnt show either ( tested it on two servers )
Grumpy
If the file doesn't exist, the second `RewriteCond` will fail (because it's checking if the file exists). If you want your script to handle a non-existant file, remove the second `RewriteCond`.
Daniel Vandersluis
well still not working. The .htaccess wont execute test.php it just shows the original content of aa.txt
Grumpy
found the solution and its working nowsolution from vandersluis ( dutch name? ) was very helpfulthe link to test.php must contain full url like var/www/domain/www/test.php
Grumpy
A: 
RewriteEngine On
RewriteCond %{REQUEST_URI} !test.php #Do not rewrite the test.php file
RewriteCond %{REQUEST_URI} -f        #Requested filename exists
RewriteRule (.*) test.php?f=$1 [QSA,L]
Vinko Vrsalovic
HI, it gives an error
Grumpy