[英]How to handle login logout session and gcache in PHP?
我使用gcache將整個網站頁面緩存為HTML,然后我僅閱讀並顯示給用戶。 看起來像這樣:
$enableCache = true;
if ($enableCache)
{
include("gcache.php");
$cache = new gCache;
$cache->folder = "temp/";
$id = join("", $_GET);
$id = ereg_replace("[^A-Za-z0-9]", "", $id);
$cache->contentId=$id;
$cache->timeout = 5;
/* its mean gCache cached the whole page */
/* so, gcache, decide if he must response the compressed or */
/* uncompressed cache*/
$cache->isPage = true;
if ($cache->Valid()) {
echo $cache->content;
die;
}
$cache->capture();
}
並且工作正常。 現在,我在網站標題中添加了“登錄”鏈接。 當人員單擊它時,它將人員重定向到他/她提供信用的子頁面,設置了會話參數(在調用session_start之前):
$_SESSION['theUser'] = $userId;
header( "refresh:1;url=http://mysite.com");
然后將人重定向到mysite.com。 但是問題是他/她看到站點來自緩存。 因此,在右上角再次有“登錄”,但是我設置了當設置$ _SESSION ['theUser']時,它應該顯示它並提供注銷鏈接。 但它不會顯示,因為它會將未登錄的網站版本返回給用戶。
如何解決這個問題?
我認為以這種方式使用緩存的原因是為了最大程度地減少服務器負載和響應時間。 但這可以通過不使用三次奇偶校驗插件/類/東西的更簡單方法來實現:
<?php
global $cachefile;
//encode cache file name with sha1
$cachefilename = sha1($_SERVER['REQUEST_URI']);
//remove trailing slash
$cachefile = rtrim(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) && filesize($cachefile)>100 && time() - $cachetime < filemtime($cachefile) ) {
readfile($cachefile);
exit;
}
function cacheOutputtoFile() {
global $cachefile;
$webpage = ob_get_contents();
if ($fp = fopen($cachefile, 'w+'))
{
// Do an exclusive lock
if (flock($fp, LOCK_EX))
{
// Truncate file
ftruncate($fp, 0);
fwrite($fp, $webpage);
fclose($fp);
}
}
}
ob_start();
register_shutdown_function("cacheOutputtoFile");
注意 :您必須使用register_shutdown_function()
而不是將cacheOutputtoFile()
用作ob_start()
參數,因為調用回調函數時套接字已經關閉,那么客戶端不會獲得echo $webpage
輸出。
用法 :將此文件放在您的根服務器文件夾中(或您想要的任何位置),並在每個要緩存的頁面的頂部都要求它一個。
require_once("cacheable.php");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.