将一些PHP作为PNG文件提供

将一些PHP作为PNG文件提供

问题描述:

I'm currently trying to get a small script working on my server, the point would be to serve a random PNG at a certain adress, for example https://domain.me/image/.

In /image/, I have this index.php, that does the job pretty well and outputs what I want:

<?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;
?>

(my PNGs are as you guessed stored in /image/src/)

I'm now trying to run that script when someone calls https://domain.me/image/script.png (some websites require a PNG extension at the end of the URL), and can't really figure out how to proceed.

If your using apache, you can use htaccess files to redirect your request:

RewriteEngine On    
RewriteRule script.png index.php

That should redirect from index.png to index.php

If you are running a LAMP server, you might be able to get it working using a url rewrite: http://httpd.apache.org/docs/2.0/misc/rewriteguide.html.

Similar to this question: .htaccess rewrite image file to php script