Reputation: 171
So I have a site that requires login to view, which has a photo gallery. In order to protect those photos I've moved them outside the web root and use a php script to display them. Something like this.
photogallery.php
echo '<img src="photo.php?id=X"/>';
photo.php
$id = (int)$_GET['id'];
$photo = getPhotoDataFromDb($id);
$path = DIRECTORY.basename($photo['filename']);
// Make sure photo file exists
if (!file_exists($path) || !is_file($path))
{
logError(__FILE__.' ['.__LINE__.'] No photo found in directory ['.$path.'] for photo id ['.$id.'].');
header('HTTP/1.0 404 Not Found');
return;
}
$info = getimagesize($path);
header("Cache-control: public, no-cache;");
header("Content-type: ".$info['mime']);
readfile($path);
Everything works fine except that this is 6 to 7 times slower than just displaying the photos normally from a directory inside the web root.
So, my questions are:
Upvotes: 2
Views: 4798
Reputation: 20475
Yes your method adds time, by having the image outside of the loop you FORCE PHP to buffer each image into memory, then send it to the user, thereby increasing load on your server and creating a noticeable delay for LARGE images (assuming gallery here).
You can speed this up by having your images in the root of your website/app. To protect your images from remote hotlinking, simply use an htaccess
script (google for it). You can also create a combination of htaccess
and login permissions to keep un-approved users out of the folders containing the images.
References:
readfile()
http://php.net/manual/en/function.readfile.phpUpvotes: 4
Reputation: 21
Try using jquery plugins or javascript gallery code to display photos instead of php. PHP is a server side language, so it has to contact server to get new images, it may slow down the site.
Upvotes: -1
Reputation: 21091
Have a look at https://tn123.org/mod_xsendfile/
I've found sendfile to be slightly quicker returning files rather than doing it directly in code.
Upvotes: 1
Reputation: 997
In a lot of cases getimagesize(); takes ages. Try to avoid it, and notice if there is any speed difference.
This happens most often with remote images, so not entirely sure you're experiencing the same problem.
Upvotes: 1
Reputation: 522
Images should be served directly form file rather than by readfile.
Upvotes: 1