doushua7737 2012-04-12 13:11
浏览 26
已采纳

用于显示图像的PHP脚本很慢

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.
  • 写回答

5条回答 默认 最新

  • dtll2016 2012-04-12 13:31
    关注
    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:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办