Reputation: 173
I wanted to cache my PHP output. I am just interested in simple PHP solution. No Memcache/Redis/APC for now. Currently I am doing like this,
<?php
$timeout = 3600; // One Hour
$file = md5($_SERVER['REQUEST_URI']);
if (file_exists($file) && (filemtime($file) + $timeout) > time()) {
// Output the existing file to the user
readfile($file);
exit();
} else {
// Setup saving and let the page execute
ob_start();
// HTML Output
$content = ob_get_flush();
file_put_contents($file, $content);
}
?>
It is working fine.
But, what if we have logged in user information on this page. Any further requests will get data from this file & it may contain that logged in user's information. How to deal with this?
Do we have to create cache files per session/user?
Upvotes: 0
Views: 1049
Reputation: 36
Try this code - cache per user session.
$timeout = 3600; // One Hour
$_uuid = isset($_SESSION['uuid']) ? $_SESSION['uuid'] : uniqid() . "_" .time();
$_SESSION['uuid'] = $_uuid;
$file = $_uuid . "_" . md5($_SERVER['REQUEST_URI']);
if (file_exists($file) && (filemtime($file) + $timeout) > time()) {
// Output the existing file to the user
readfile($file);
exit();
} else {
// Setup saving and let the page execute
ob_start();
// HTML Output
$content = ob_get_flush();
file_put_contents($file, $content);
}
?>
Upvotes: 1
Reputation: 163272
If you have some specific reason for caching the output of a page per-user, consider caching the data that this paged is based on. That is, make an application layer cache rather than doing it at the web server or output stage. Otherwise, don't worry about it... set the appropriate headers and let the browser worry about caching. You're creating more of a problem by trying to re-invent the wheel here when you have a page that is being generated for only a single user anyway.
Upvotes: 2