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

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

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

But I'm not sure how to capture all the image file requests and redirect them to
, 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