【发布时间】:2017-12-26 09:59:59
【问题描述】:
我正在尝试像这样通过 php 提供图像:
img.php
<?php
session_start();
$file=$images_path.$_GET['id'].".jpg";
$lastModified = gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT';
header("Cache-Control: private");
header("Content-type: image/jpeg");
header("ETag: ".md5_file($file));
header("Last-Modified: $lastModified");
header('Expires: ' . gmdate("D, d M Y H:i:s", ((60*60*24*1)+strtotime($lastModified))));//1 day expire
$db=new PDO("mysql:host=".$host.";dbname=".$db_name,$db_user,$db_psw);
$e=explode("/",$_GET['id']);
$post=$e[0];
$e=explode("_",$e[1]);
$user=$e[0];
$q="SELECT p.id FROM post p INNER JOIN files f ON p.id=f.post WHERE p.id=".$post." AND ";
if(!isset($_SESSION['id'])) $q.="p.privacy=1";
else
{
$q.="(";
$q.="p.user=".$_SESSION['id'];
$q.=" OR p.privacy=1";
$q.=" OR (p.privacy=2 AND p.user IN (".$_SESSION['id'];
if(count($_SESSION['friends'])>0) $q.=",".implode(",",array_keys($_SESSION['friends']));
$q.="))";
$q.=" OR ".$_SESSION['id']." IN(SELECT tag FROM tags WHERE post=p.id)";
$q.=")";
}
$q.=" AND f.user=".$user." AND (f.date IS NOT NULL"; if(isset($_SESSION['id'])) $q.=" OR f.user=".$_SESSION['id']; $q.=")";
$q.=" LIMIT 1";
$sql=$db->prepare($q); $sql->execute(); $post=$sql->fetch(PDO::FETCH_ASSOC);
if(!isset($post['id'])) {header("location:".$localhost); exit;}
if(file_exists($file))
{
header('Content-Type:image/jpeg');
readfile($file);
}
?>
index.php
<img src="img.php?id=1/1_1"><br>
<img src="img.php?id=1/1_2"><br>
<img src="img.php?id=1/1_3"><br>
但是速度很慢,而且不缓存图片,怎么办?
谢谢
更新 1
好的readfile(),我修好了
我更新了完整代码,这是必需的,因为我提供的图像不在公共根文件夹中,我必须检查当前登录的用户是否有权使用 mysql 查询中的会话查看图像
更新 2
我想要: 如果 files.date 为 NULL 则不缓存图像,或者缓存它并在它更改时强制重新加载 如果 files.date 不为空,则永远缓存图像 我不知道我应该使用哪些标题以及在哪里使用
更新 3
更新 4
如果资源被缓存,我想避免执行查询,那么使用会话变量来缓存图像的url呢?
【问题讨论】: