Question

Is it possible to redirect an image to a dynamically generated image(using PHP)?

I have a dynamically created image and it has an extension ".PHP" (obviously) and that server is not under my control. So I want to redirect "somename.jpg" (on my server) to "remoteserver/dynamicimage.php" (on some remote server not under my control) so that I can right away link it as <img src="somename.jpg"/> and the dynamically generated image is shown.

Please let me know if this is possible.

Was it helpful?

Solution

Browsers follows redirects for images. Create a php-file called "somename.jpg" and add:

<?php
header('Location: http://www.otherserver.com/image.php');

Use the Apache directive ForceType in an .htaccess file to tell the server to process the .jpg file as php:

<Files somename.jpg>
    ForceType application/x-httpd-php
</Files>

Or just call the file somename.php if you don't really need the .jpg extension.

You could probably accomplish this using mod_alias as well, although I haven't tried it:

Redirect somename.jpg http://www.otherserver.com/image.php

This would go in an .htaccess file as well.

OTHER TIPS

The header function controls the HTTP header, which is what the browser uses to determine the file type (or should, in any case.) It can be used to tell the browser that the script is generating an image file to be downloaded, rather than HTML script output:

header('Content-type: image/jpeg');
header('Content-Disposition: attachment; filename="somename.jpg"');

Try adding something like this to your .htaccess file

RewriteEngine on
RewriteRule ^(.*)\.jpg$ /scripts/$1.php

It is possible but would result in an HTTP redirect:

RewriteEngine on
RewriteRule ^somename\.jpg$ http://remoteserver/dynamicimage.php [L]

An alternative would be to use a proxy (see P flag), so that your server requests the remote resource and passes it back to the client.

Another much more complicated but incredible powerfull way would be to write some handler code which gets activated for this local image location url.

This one would fetch the data from the foreign url and outputs the data with the right mime type.

One you also write some code to cache this data basing on whatever may be feasible.

This way you would never give away the real location of the image and you could even use some secret credentials like logindata or third party cookies which should not appear on your site.

All of this is much harder to do then to simply configure a redirection in the apache config. We did stuff like this in cases where the url's would leak private informations otherwise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top