Serving images directly from server with getting path from PHP script
as most of you probably know, we can serve images from PHP using constructs like this:
RewriteRule ^images/([a-zA-Z0-9]+)\.jpg script.php?image=$1
And then in PHP:
header('Content-Type: image/png');
$image=imagecreatefromjpeg($pathComputedSomewhereElse);
imagejpeg($image);
That's dead simple, but that's not my problem - i simply don't want to confuse you.
My question is:
How can I, if it is possible, serve such image directly, using PHP only to fetch image path? I want Apache to do the work, not PHP reading file and outputting data as binary stream.开发者_如何学C Prototype markup would be as follows [same .htaccess]:
header('Content-Type: image/png');
header('Location: '.$pathComputedSomewhereElse);
If you have mod_xsendfile
installed in your Apache, you can do exactly what you need without the client seeing the path they are redirected to.
header("X-Sendfile: /path/to/your/filename");
header("Content-type: image/jpeg");
See a background article here
Alternatively, if the client is allowed to see the new URL, I don't see why using a 302
header wouldn't work:
header("Location: http://example.com/path/to/your/imagefile.jpg");
die();
header("Content-Type: image/jpeg\n");
header("Content-Transfer-Encoding: binary");
$fp=fopen("images/$image.jpg" , "r");
if ($fp)
fpassthru($fp);
using the gdlib functions for this is overkill :-)
if you dont want to modify the file you use:
header("Content-Type: image/jpeg\n");
header("Content-Transfer-Encoding: binary");
readfile("images/$image.jpg" , "r");
Why not try..
RewriteRule ^images/([a-zA-Z0-9]+)\.jpg /new/image/directory/$1.jpg [L]
in htaccess
RewriteRule ([^.]+)\.jpg$ script.php?image=$1
$_REQUEST['image'] contains path without ".jpg", add and gather path ;)
精彩评论