views:

35

answers:

4

Hello everyone,

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. Prototype markup would be as follows [same .htaccess]:

header('Content-Type: image/png');
header('Location: '.$pathComputedSomewhereElse);
A: 
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");
DoXicK
yes, but that's still sending binary stream through php, and that's what i would like "not to" do.
Tomasz Kowalczyk
He doesn't want to use PHP for delivering the file.
Pekka
A: 

Why not try..

RewriteRule ^images/([a-zA-Z0-9]+)\.jpg /new/image/directory/$1.jpg [L]
fire
yes, but i need to fetch image path form php script. your solution solves only the "introduction" of my question. ;]
Tomasz Kowalczyk
+1  A: 

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();
Pekka
that's good idea, i'll check if that module is instaled and enabled.
Tomasz Kowalczyk
@Tomasz yeah. Alternatively, as I said, `header("Location:")` should work as well, but it will reveal the URL to the user
Pekka
unfortunately it came out later that we don't have access to client's server so we had to simple rename files and change references in code, but still thanks for helping me - accepted, sir!
Tomasz Kowalczyk
A: 

in htaccess

RewriteRule ([^.]+)\.jpg$ script.php?image=$1

$_REQUEST['image'] contains path without ".jpg", add and gather path ;)

nerkn
yes, but PHP script will be used for computing the path - that's the clue ;]
Tomasz Kowalczyk