note 106275 deleted from function.ob-start by cmb

From: Date: Mon, 21 Jan 2019 15:30:44 +0000
Subject: note 106275 deleted from function.ob-start by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-210098@lists.php.net to get a copy of this message
Note Submitter: loksly at gmail dot com ---- It's easy to add a function that caches the whole page you're going to generate so resources are saved. I wrote it in a file called "cacheable.php", and I included in each file that I want to be cached. It cannot manage files with ob_start inside. Here is the code: file "cacheable.php": ---------------------------------- <?php global $cachefile; $cachefilename = urlencode($_SERVER['REQUEST_URI'])."-".md5($_SERVER['REQUEST_URI']); $cachefile = sys_get_temp_dir ().DIRECTORY_SEPARATOR.$cachefilename.'.cache'; // How long to keep cache file? $cachetime = 60*5; //5min // Is cache file still fresh? If so, serve it. if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) { readfile($cachefile); exit; } function cacheOutputtoFile() { global $cachefile; $webpage = ob_get_contents(); if ($fp = fopen($cachefile, 'w+')) { if (flock($fp, LOCK_EX)) { // do an exclusive lock ftruncate($fp, 0); // truncate file //compress unnecesary spaces $busca = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s'); $reemplaza = array('>','<','\\1'); $webpage = preg_replace($busca, $reemplaza, $webpage); fwrite($fp, $webpage); fclose($fp); } } echo $webpage; } ob_start(); register_shutdown_function("cacheOutputtoFile"); //note you must use register_shutdown_function instead of using "cacheOutputtoFile" as parameter of ob_start as socket is already closed when callback function is called, then the client not get the echo $webpage output. ?> ---------------------------------- usage: <?php require_once(realpath(dirname(__FILE__).DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR."cacheable.php"); ?> ----------------------------------

« previous php.notes (#210098) next »