tags:

views:

77

answers:

4

How to cache PHP page which has mysql query. Any example will be great and helpful.

A: 

memcache your html out and then do something like this:



    $memcache = memcache_connect('localhost', 11211);


    $page  = $memcache->get('homepage');

    if($page == ""){
        $mtime = microtime();
        $page = get_home();
        $mtime = explode(" ",$mtime);
        $mtime = $mtime[1] + $mtime[0];
        $endtime = $mtime;
        $totaltime = ($endtime - $starttime);
        memcache_set($memcache, 'homepage', $page, 0, 30);
        $page .= "\n";
    }
    else{

        $mtime = microtime();
        $mtime = explode(" ",$mtime);
        $mtime = $mtime[1] + $mtime[0];
        $endtime = $mtime;
        $totaltime = ($endtime - $starttime);
        $page .= "\n<!-- served from memcache ($totaltime) -->";

    }

    die($page);
sathia
A: 

My preference is to use a caching reverse proxy, like Varnish.

As far as a pure PHP solution, you could have some code at the end of your script that caches the final output, and code at the beginning that checks to see if the page is cached. If the page was found in cache, send it and exit rather than running the queries again.

<?php

function cache_file() {
    // something to (hopefully) uniquely identify the resource
    $cache_key = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']);
    $cache_dir = '/tmp/phpcache';

    return $cache_dir . '/' . $cache_key;
}

// if we have a cache file, deliver it
if( is_file( $cache_file = cache_file() ) ) {
    readfile( $cache_file );
    exit;
}

// cache via output buffering, with callback
ob_start( 'cache_output' );

//
// expensive processing happens here, along with page output.
//

function cache_output( $content ) {
    file_put_contents( cache_file(), $content );
    return $content;
}

Obviously this needs lots of customization for your setup, including cache expiration, a $cache_key that meets your needs, and error detection so bad pages aren't cached.

Adam Backstrom
A: 

You can cache result of a sql query and then produce HTML from this data, or you can cache all page using PHP's ob* handlers.

Tomasz Kowalczyk