English 中文(简体)
如何使用 PHP 动态地生成图片并将 <img> 标签指向该图片?
原标题:
  • 时间:2009-04-30 12:11:14
  •  标签:

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.

请告诉我这是否可能。

最佳回答

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

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

使用Apache指令ForceType在.htaccess文件中告诉服务器将.jpg文件处理为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.

问题回答

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.

另一种更加复杂但极其强大的方法是编写一些处理程序代码,以激活此本地图像位置 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.





相关问题
热门标签