将一些PHP作为PNG文件提供


Serve some PHP as a PNG file

我目前正在尝试在我的服务器上运行一个小脚本,重点是在某个地址提供一个随机的PNG,例如https://domain.me/image/.

在/image/中,我有一个index.php,它做得很好,并输出我想要的:

<?php
$max = 30;
$image = rand(1, $max);
$name = '/var/www/image/src/'.$image.'.png';
$fp = fopen($name, 'rb');
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
fpassthru($fp);
exit;
?>

(正如你所猜测的,我的PNG存储在/image/src/中)

我现在正试图在有人打电话时运行该脚本https://domain.me/image/script.png(有些网站要求在URL末尾添加PNG扩展名),并且无法真正弄清楚如何继续。

如果你使用apache,你可以使用htaccess文件重定向你的请求:

RewriteEngine On    
RewriteRule script.png index.php

这应该从index.png重定向到index.php

如果您正在运行LAMP服务器,则可以使用url重写使其工作:http://httpd.apache.org/docs/2.0/misc/rewriteguide.html.

类似于这个问题:.htaccess将图像文件重写为php脚本