haudenschilt
haudenschilt

Reputation: 171

PHP script to display images is slow

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:

  1. Is there something wrong with my code, or does this method always add more time?
  2. How can I speed things up? Is there a safe way to cache the images? I believe Gallery 2 does this somehow.

Upvotes: 2

Views: 4798

Answers (5)

Jakub
Jakub

Reputation: 20475

  1. 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).

  2. 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:

Upvotes: 4

pandu
pandu

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

barryhunter
barryhunter

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

Gert Van de Ven
Gert Van de Ven

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

Karol Sikora
Karol Sikora

Reputation: 522

Images should be served directly form file rather than by readfile.

Upvotes: 1

Related Questions