Snazzy Sanoj Snazzy Sanoj - 4 years ago 106
HTML Question

PHP: Handling Dynamic File Request

I'm developing a Web Application where the all the image requests are to be handled by the

index.php
page directly. For example, if a request is made for file
image1.png
, it is to be redirected to
index.php
, where the details of the
image1.png
file are displayed.

I've written code for displaying the details of a file, when the filename is passed as a GET parameter to
index.php
file.

But I'm not sure how to capture all the image file requests and redirect them to
index.php
, and at the same time, pass the requested filename as a parameter via GET.

Any help would be greatful. :)

Answer Source

Try the following in the .htaccess file in the document root:

RewriteEngine On
RewriteRule (.+\.png)$ index.php?file=$1 [L]

This internally rewrites all .png files to index.php passing the full URL as a URL parameter. (Although this notably excludes the slash prefix. You can manually include this if required. eg. ?file=/$1.)

To extend this to include .jpg files as well then change the RewriteRule pattern:

RewriteRule (.+\.(png|jpg))$ index.php?file=$1 [L]

EDIT: To route all non-PHP files you can do something like:

RewriteCond %{REQUEST_URI} (.*)
RewriteRule !\.php$ index.php?file=%1 [L]

For all non-PHP files (note the negated regex with a ! prefix), the request is rewritten, passing the requested URL to index.php. Note that a negated regex cannot include a capturing group, hence the requirement for a separate condition.

Note that this includes the slash prefix (since it is included as part of the REQUEST_URI variable), whereas the examples above did not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download