ตัวอย่างต่อไปนี้ เป็นแนวทางสำหรับการกำหนด expired header ให้กับรูปภาพ ที่แสดงในหน้าเว็บไซต์
ทำให้ บราวเซอร์เลือกใช้งานรูปภาพจากเครื่อง โดยดูจากวันที่ expired ของรูปภาพที่เรากำหนด ถ้ารูปที่อยู่
ในเครื่องหรือที่ cache ไว้ในตอนแรก ยังไม่หมดอายุ ก็จะทำการดึงรูปจากที่เครื่องมาใช้ แทนการไปโหลด
ที่ server ใหม่ทุกครั้ง
1. สรัางไฟล์ index.php ตามโค้ดด้านล่าง แล้วในไปวางไว้ในโฟลเดอร์รูปภาพ
<?php
if(!isset($_GET['pic']) || $_GET['pic']==""){
$_GET['pic']="photoNotAvailable.jpg"; // ชื่อรูปภาพที่ต้องการแสดงกรณีไม่มีรูป
}
function imgType($imgName){
$imgName=strtolower($imgName);
$imgTypeShow="";
if(preg_match("/.gif/",$imgName)){
$imgTypeShow="gif";
}
if(preg_match("/.png/",$imgName)){
$imgTypeShow="png";
}
if(preg_match("/.jpg/",$imgName)){
$imgTypeShow="jpeg";
}
if(preg_match("/.jpeg/",$imgName)){
$imgTypeShow="jpeg";
}
return $imgTypeShow;
}
if(imgType($_GET['pic'])){
$last_modified_time = filemtime($_GET['pic']);
$etag = md5_file($_GET['pic']);
header("Content-type: image/".imgType($_GET['pic']).";");
header("Cache-Control: must-revalidate");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
$offset = 60 * 60 * 24 * 30; // กำหนดอายุ 30 วัน ดูตัวคูณตัวหลังสุด * 30
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header($ExpStr);
if($_GET['pic']!=""){
if(is_file($_GET['pic'])){
$abs_url="htttp://www.yourdomain.com/images/";// กำหนด path หรือตำแหน่งจริงของรูปภาพที่จะแสดง
echo file_get_contents($abs_url.$_GET['pic']);
}
}
}
?>
2. การใช้งาน ตัวอย่างรูปภาพตาม url นี้ https://www.ninenik.com/images/logo_01_Mon.gif
นำไฟล์ index.php ไปไว้ที่โฟลเดอร์ images
เรียกใช้งาน รูปภาพผ่าน url ใหม่เป็น
https://www.ninenik.com/images/?pic=logo_01_Mon.gif
เท่านี้ก็จะได้รูปภาพที่มีการกำหนด expired header มาแสดง