note 106275 added to function.ob-start
| From: | loksly at gmail dot com | Date: | Mon, 24 Oct 2011 12:30:05 +0000 |
| Subject: | note 106275 added to function.ob-start | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-184089@lists.php.net to get a copy of this message | ||
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:
require_once(realpath(dirname(__FILE__).DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR."cacheable.php");
----------------------------------
----
Server IP: 80.64.47.13
Probable Submitter: 147.84.200.85
----
Manual Page -- http://www.php.net/manual/en/function.ob-start.php
Edit -- https://master.php.net/note/edit/106275
Del: integrated -- https://master.php.net/note/delete/106275/integrated
Del: useless -- https://master.php.net/note/delete/106275/useless
Del: bad code -- https://master.php.net/note/delete/106275/bad+code
Del: spam -- https://master.php.net/note/delete/106275/spam
Del: non-english -- https://master.php.net/note/delete/106275/non-english
Del: in docs -- https://master.php.net/note/delete/106275/in+docs
Del: other reasons-- https://master.php.net/note/delete/106275
Reject -- https://master.php.net/note/reject/106275
Search -- https://master.php.net/manage/user-notes.php