views:

59

answers:

1

I am trying to do the following in my web application:

<img src="static.example.com/image01.jpg?width=300&height=300" />

Is it possible to have my server (I use Apache in a shared hosting environment) run a PHP script when accessing a .jpg (or any filetype that I chose) instead of just serving the file?

I know that the PHP script has to set the right headers etc, I'm just wondering how it can be run in the first place.

I know this can be done as so :

<img src="static.example.com/get_image.php?name=image_01.jpg&width=300&height=300" />

but that's not how I would like to have it.

+3  A: 

You could use mod_rewrite provided you are in a subdirectory, or that is all your other static.example.com will be doing.

Add something like this to your .htaccess in that subdirectory.

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{query_string} ^height=([^&]+)&width=([^&]+)
   RewriteRule (.*\.jpg|.*\.png|.*\.gif) controller.php?name=$1&height=%1&width=%2
</IfModule>

EDIT: Try the above. Like everything else, untested... :)

The order of the GET parameters becomes important.

test.jpg?height=100&width=120

should get turned into

controller.php?name=test.jpg&height=100&width=120


Another approach would be to make apache serve .jpg as php scripts for that directory. Just look in your httpd.conf or php.conf and look for .php. Find that directive, and duplicate it within a <Directory> for .jpg. I've never actually tried this for a single directory, but ultimately it would be faster than the mod_rewrite route.

Something like:

<Files *.jpg>
SetOutputFilter PHP
SetInputFilter PHP
</Files>
AddType application/x-httpd-php .jpg
Daren Schwenke
I'm assuming the .* can be changed to .*jpg or other regular expressions to match the extensions I want, correct?
jd
jd
what happens if you print $_GET['q']?
Daren Schwenke
I think what is happening, is because we are specifying ?stuff=asdf we are overwriting the original query string. I modified the code above to propogate the original parameters with the new one. Hope it works.
Daren Schwenke