How to set up browser caching with PHP

How to set up browser caching with PHP

$lastModified = time() + 30;

header(‘Last-Modified: ‘ . gmdate(‘D, d M Y H:i:s’, $lastModified) . ‘ GMT’); //After this line is set, it will go to the server to check whether it has expired (whether the file has been modified), and if it is not expired, it will take the local file (the server needs to return the header)

header(‘Expires: ‘ . gmdate(‘D, d M Y H:i:s’, $lastModified) . ‘ GMT’); //After this line is set, no longer go to the server to check whether it expires, and directly fetch the local file.

header(‘Cache-Control: max-age=1’); // (relative to local time)

There is also an Etag, which compares strings, not time.

The following code is to disable point back-off after caching.

header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');

// HTTP/1.1
header('Cache-Control: private, no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0, max-age=0', false);

header(“Content-Type: application/json”);// Sometimes you have to add this sentence, otherwise it won’t work (see nginx configuration)

Full example:

<?php
// this is a cache test 
$cache_time = 60*10; //Ten-minute caching
$modified_time = @$_SERVER['HTTP_IF_MODIFIED_SINCE']; 
if( strtotime($modified_time)+$cache_time > time() ){ 
    header("HTTP/1.1 304"); 
    exit; 
} 
header("Last-Modified: ".gmdate("D, d M Y H:i:s", time() )." GMT"); 
header("Content-Type: application/json");//Sometimes it is necessary to add this sentence, otherwise it will not work
 echo "<br />"; echo date('Y-m-d H:i:s',time());  ?>

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *