ตัวอย่างต่อไปนี้ เป็นแนวทางสำหรับการกำหนด expired header ให้กับรูปภาพ ที่แสดงในหน้าเว็บไซต์
ทำให้ บราวเซอร์เลือกใช้งานรูปภาพจากเครื่อง โดยดูจากวันที่ expired ของรูปภาพที่เรากำหนด ถ้ารูปที่อยู่
ในเครื่องหรือที่ cache ไว้ในตอนแรก ยังไม่หมดอายุ ก็จะทำการดึงรูปจากที่เครื่องมาใช้ แทนการไปโหลด
ที่ server ใหม่ทุกครั้ง
1. สรัางไฟล์ index.php ตามโค้ดด้านล่าง แล้วในไปวางไว้ในโฟลเดอร์รูปภาพ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <?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' ])){ 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 มาแสดง