Last active
July 15, 2020 06:38
-
-
Save gphg/1e59295aabcbc1a207239d5192424608 to your computer and use it in GitHub Desktop.
A simple Pico CMS plugin for HTTP caching.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Pico HTTP page caching plugin | |
* | |
* Web server (well known are Apache2 and Nginx) come with | |
* mod_cache and mod_expires specialize for static files. | |
* Last-Modified HTTP header is part of it. | |
* | |
* This plugins gives more control on Pico http page caching. | |
* | |
* @author Hexat | |
* @license DBAD | |
* @version 0.0.2 | |
*/ | |
class HttpPageCaching extends AbstractPicoPlugin | |
{ | |
const API_VERSION = 2; | |
public function onMetaParsed(array &$pageData) | |
{ | |
// Should it be cached? | |
$doCache = isset($pageData['httpCaching']) ? $pageData['httpCaching'] : null; | |
if ($doCache !== true || (is_null($doCache) && ($this->getPluginConfig('global', false) !== true))) { | |
return; | |
} | |
// Get lastModification time | |
if (!isset($pageData['last_modified'])) { | |
if (isset($pageData['meta']['last_modified'])) { | |
$pageData['last_modified'] = $pageData['meta']['last_modified']; | |
} elseif (isset($pageData['httpCaching']['last_modified'])) { | |
$pageData['last_modified'] = $pageData['httpCaching']['last_modified']; | |
} if (is_file($this->getRequestFile())) { | |
$pageData['last_modified'] = filemtime($this->getRequestFile()); | |
} | |
} | |
// Read client-side HTTP headers for cache | |
if (!is_null($pageData['last_modified']) && isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $pageData['last_modified'] <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { | |
header('HTTP/1.1 304 Not Modified'); | |
exit; | |
} | |
// Set headers | |
$pramaCache = (isset($pageData['httpCaching']['pragma'])) ? $pageData['httpCaching']['pragma'] : 'public'; | |
header('Pragma: '. $pramaCache); | |
if (isset($pageData['httpCaching']['expiration'])) { | |
$maxAge = $pageData['httpCaching']['expiration'] - $_SERVER['REQUEST_TIME']; | |
header('Cache-Control: max-age='.$maxAge.', public'); | |
header('Expires: '.gmdate('D, d M Y H:i:s', $pageData['httpCaching']['expiration']).' GMT'); | |
} | |
if (isset($pageData['last_modified']) && !is_null($pageData['last_modified'])) { | |
header('Last-modified: '.gmdate('D, d M Y H:i:s', $pageData['last_modified']).' GMT'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Cache individual page
Cache page globally by default