Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I "echo" a .jpg image through php without processing it?

Tags:

php

Imagine the following:

<img src="/image.php?image=5.jpg" />

Now, in image.php:

header('content-type: image/jpeg');
$image = imagecreatefromjpeg($_GET['image']);
imagejpeg($image,NULL,100);

This works, but this way the script loads the image, processes it, then echoes it. Can this be done without processing the image?

The reason why I want to do it this way is that I don't want people to know where the images are located, therefore I don't want to write the full path into the img src attribute.

I just need to send raw images to the browser, but without revealing their true location.

like image 386
Frantisek Avatar asked Aug 15 '11 18:08

Frantisek


3 Answers

What about something like http://www.php.net/manual/en/function.readfile.php

From the example

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>
like image 187
Code Magician Avatar answered Nov 14 '22 20:11

Code Magician


Yes, you can. Just readfile instead of imagecreatefromXXX+imagejpeg.

header('Content-Type: image/jpeg');
$src = /* process $_GET['image'] to recover the path */;
readfile($src);

The /* process $_GET['images'] to recover the path */ part implies any sanitizing you need to do on the input to avoid that someone requests a forbidden file. If your script input is a file path, this may mean checking from a predefined list, stripping of possible directory separators, checking against a regex, etc. Another way would be to store paths inside a database and pass the script a simple id, and recover the file path with it. This might be a better idea, as users will see no mention of any file path on the script URL (if you just pass a path, people can actually guess where files are, and that's what you're trying to prevent).

like image 42
zneak Avatar answered Nov 14 '22 20:11

zneak


Sure, using readfile. Don't forget to restrict the allowed image names. Otherwise, you'd be creating a directory traversal vulnerability.

header('content-type: image/jpeg');
$img = preg_replace('/[^0-9a-z\._\-]/', '_', $_GET['image']);
readfile($img);
like image 42
phihag Avatar answered Nov 14 '22 20:11

phihag