Archive for May, 2009

0060 | PHP Dynamic page static HTML generator

Monday, May 25th, 2009 Posted in PHP Coding, Programming, Web Server | 4 Comments »

ชื่อยาวเป็นวา code อะไรวะ (วันหลังมา search จะเจอมั้ยเนี่ยตู 555)

code นี้แปะด้านบนสุดของไฟล์ (จะใส่ใน auto prepend เลยก็ยังไหว)

<?php
$_cachetime = 43200;
$_info = parse_url($_SERVER["REQUEST_URI"]);
if (!isset($_info['query'])) $_info['query'] = '';
$_path = end(explode('/', $_info['path']));
$_info['query'] = str_replace('&nocache', '', $_info['query']);
$_info['query'] = str_replace('nocache&', '', $_info['query']);
$_info['query'] = str_replace('nocache', '', $_info['query']);
$_cachename = sprintf("%x", crc32($_path."?".$_info['query']));
$_cachefolder = '/path/to/cache/'.substr($_cachename,0,2).'/';
$_cachefile = $_cachefolder.$_cachename;
if ($_SERVER["REQUEST_URI"] != '/' && $_SERVER["REQUEST_METHOD"] == 'GET' &&
    !isset($_GET["nocache"]) &&
    file_exists($_cachefile) && filemtime($_cachefile) > time() - $_cachetime) {
        readfile($_cachefile);
        exit();
}
function fetch_cache($_buffer) {
        global $_cachefile, $_cachefolder;
        umask( 0);
        if (!file_exists($_cachefolder))
                mkdir($_cachefolder,0777, true);
        if ($_h = fopen($_cachefile, "w")) {
                fwrite($_h, $_buffer);
                fclose($_h);
        }
        return $_buffer;
}
ob_start('fetch_cache');
?>

code นี้ใส่ด้านท้าย (ใน auto append ก็ได้นะครับ)

<?php
ob_end_flush();
?>

* แก้ไขเพิ่ม 2009/05/28

Tags: , ,