Point an <img> tag to a image dynamically generated by PHP?

落爺英雄遲暮 提交于 2019-12-23 17:21:36

问题


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.


回答1:


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.




回答2:


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"');



回答3:


Try adding something like this to your .htaccess file

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



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/806599/point-an-img-tag-to-a-image-dynamically-generated-by-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!