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&am开发者_如何学Gop;height=300" />
but that's not how I would like to have it.
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
精彩评论