Can I "echo" a .jpg image through php without processing it?
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 scrip开发者_如何学编程t 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.
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).
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);
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;
}
?>
精彩评论