I'm trying to serve images through php like this:
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>
but it's very slow, and doesn't caches images, how should I do ?
Thanks
UPDATE 1
Ok about readfile()
, I fixed it
I updated with full code, which is required because images I'm serving aren't in the public root folder, and I have to check if current logged in user has rights to view the image using session in mysql query
UPDATE 2
I'd like to have: if files.date IS NULL then don't cache image , or cache it and force reload when it changes if files.date IS NOT NULL then cache image for ever I don't know which headers should I use and where
UPDATE 3
Here is a screenshot of headers of an image
UPDATE 4
I'd like to avoid the query execution if resource is cached, what about using session variables for caching url of images?