2013-01-19 75 views
2

我一直在使用一個基本的緩存系統在我的網站基於this link自動創建PHP

它迄今行之有效的寄託都我想要做的緩存文件。

$cachefile = 'cache/'. basename($_SERVER['QUERY_STRING']) . '.html'; 
$cachetime = 1440 * 60; 

if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) { 
    include($cachefile); 
    echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->"; 
    exit; 
} 

ob_start(); 

// My html/php code here 


$fp = fopen($cachefile, 'w'); // open the cache file for writing 
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file 
fclose($fp); // close 
ob_end_flush(); // Send to browser 

不過,我有一對夫婦的更詳細的MySQL的查詢網頁,我已經花了很多時間公平位優化它但是它仍然需要大約10秒的時候我查詢它在MySQL,甚至更長的運行網站。有時候,當我收到下面的消息時,它似乎會超時。

The proxy server received an invalid response from an upstream server. 
The proxy server could not handle the requestGET http://www.example.com 

Reason: Error reading from remote server 

這是不是一個巨大的問題,因爲,因爲我只用了第一人稱上面的緩存系統,點擊它一天獲得的延遲和休息的時間得到了用戶的緩存頁面,以便對他們來說實際上是相當快的。

我想讓自己不必每天都要成爲第一個訪問頁面並自動執行此過程的人,因此每天17:00(在服務器上)文件被寫入緩存。

我該如何做到最好?

+0

如果你有linux服務器 - cron作業 – vodich

回答

3

我建議你使用Php Speedy或者這可能會幫助:

<?php 
function getUrl() { 
    if (!isset($_SERVER['REQUEST_URI'])) { 
    $url = $_SERVER['REQUEST_URI']; 
    } else { 
    $url = $_SERVER['SCRIPT_NAME']; 
    $url .= (!empty($_SERVER['QUERY_STRING']))? '?' . $_SERVER[ 'QUERY_STRING' ] : ''; 

    } 
    return $url; 
} 

//getUrl gets the queried page with query string 
function cache ($buffer) { //page's content is $buffer 
    $url = getUrl(); 
    $filename = md5($url) . '.cache'; 
    $data = time() . '¦' . $buffer; 
    $filew = fopen("cache/" . $filename, 'w'); 
    fwrite($filew, $data); 
    fclose($filew); 
    return $buffer; 
} 

function display() { 
    $url = getUrl(); 
    $filename = md5($url) . '.cache'; 
    if (!file_exists("/cache/" . $filename)) { 
    return false; 
    } 
    $filer = fopen("cache/" . $filename, 'r'); 
    $data = fread($filer, filesize("cache/" . $filename)); 
    fclose($filer); 
    $content = explode('¦', $data, 2); 
    if (count($content)!= 2 OR !is_numeric($content['0'])) { 
     return false; 
    } 
    if (time()-(100) > $content['0']) { // 100 is the cache time here!!! 
     return false; 
    } 
     echo $content['1']; 
     die(); 
} 

// Display cache (if any) 
display(); // if it is displayed, die function will end the program here. 

// if no cache, callback cache 
ob_start ('cache'); 
?> 

就包括這個腳本你需要的地方緩存,並設置一個cron作業運行它的自動化。

+0

Php Speedy的唯一缺點是改變了css和js擴展。它可能會使驗證器壓抑你。 – Kemal