www.webdeveloper.com
Results 1 to 11 of 11

Thread: Page Caching

  1. #1
    Join Date
    Mar 2004
    Posts
    121

    Page Caching

    All,

    I'm writing a script to do page caching. I've got the following code - which works, but I was wondering if anyone hand any input to make it run more efficiently.

    Code:
    <?php
    error_reporting(E_ALL);
    
    // The ./ location puts the file in the root of your
    define('CACHEDIR', './');
    
    // URL of page you wish to cache
    $request =  'http://www.google.com';
    
    $cache_filename = 'cached.php';
    $cache_fullpath = CACHEDIR.$cache_filename;
    
    // Number of seconds until the cache gets stale
    $cache_timeout = 0;
    
    // Check the cache
    $response = request_cache($request, $cache_fullpath, $cache_timeout);
    
    if ($response === false) {
    	die('Request failed');
    }
    
    // Output the XML
    echo htmlspecialchars($response, ENT_QUOTES);
    
    // This is the main caching routine.
    function request_cache($url, $dest_file) {
    		$data = file_get_contents($url);
    		if ($data === false) return false;
    		$tmpf = tempnam('/tmp','YWS');
    		$fp = fopen($tmpf,"w");
    		fwrite($fp, $data);
    		fclose($fp);
    		rename($tmpf, $dest_file);
    	return($data);
    }
    
    ?>

  2. #2
    Join Date
    Dec 2006
    Location
    Escaz˙ (Costa Rica) and Mallorca (Spain)
    Posts
    3,234
    I would have expanded the cache function to automatically (1) deliver the cached page if not stale or (2) deliver a fresh version if the cache is stale or (3) a fresh version if no cached copy is present.

    I think your current version will also cause you grief retrieving he correct cached copy when requested. You need to devise a working system for naming the cached files.

  3. #3
    Join Date
    Mar 2004
    Posts
    121
    Any suggestions?

  4. #4
    Join Date
    May 2006
    Location
    Prague, Czech Republic
    Posts
    66
    I've just finished a caching class which will cache the output of any function and covers the points made by NightShift. It's not online yet, but if you can hold on a few days then I'll send you the link and you'd be welcome to use it.

  5. #5
    Join Date
    Mar 2004
    Posts
    121
    That would be much appreciated. Thank you!

  6. #6
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,742

    Cache Class

    Quote Originally Posted by NightShift58
    I would have expanded the cache function
    Something like this?
    PHP Code:
    <?php

    class Cache
    {
        
    /******************************************************
        
        CLASSNAME: 
        Cache
        
        AUTHOR:
        bokeh
        
        THREAD:
        http://webdeveloper.com/forum/showthread.php?t=138529
        
        PURPOSE: 
        To handle server-side and client-side caching of local
        pages. It also GZips all output to save on bandwidth.
        
        PERMISSIONS:
        Be certain this script has sufficient permission 
        to read from and write to the cache directory. 
        
        EXAMPLE USE (your script):
        
        <?php

        # right at the start of your script
        require_once('class.cache.php');
        
        # now call the cache class,
        # first argument: cache location, 
        # second argument: cache file duration in seconds.
        $cache = new cache('./cache/', 3600);  
        
        ?>
        
        Your script content here!
        
        <?php
        
        # right at the end of your script
        $cache->output();
        
        ?>
        
        ******************************************************/
        
        
    var $buffer;
        
        function 
    Cache($location$expires)
        {
            
    ob_start();
            if(empty(
    $_POST))
            {
                if((
    file_exists($this->filename $location md5($_SERVER['REQUEST_URI']))) 
                and (
    filemtime($this->filename) > (time() - $expires)))
                {
                    
    $this->buffer file_get_contents($this->filename);
                    
    $this->output(false);
                }
            }
        }
        
        function 
    CachePage()
        {
            if(empty(
    $_POST))
            {
                
    $fp fopen($this->filename'w');
                
    fwrite($fp$this->bufferstrlen($this->buffer));
                
    fclose($fp);
            }
        }
        
        function 
    output($cache true)
        {
            
    $this->buffer or $this->buffer ob_get_clean();
            if(
    $cache$this->CachePage();
            
    header('Etag: "'.($hash md5($this->buffer)).'"');
            if(isset(
    $_SERVER['HTTP_IF_NONE_MATCH']))
            {
                if(
    $hash == trim(stripslashes($_SERVER['HTTP_IF_NONE_MATCH']), '"'))
                {
                    die(
    header("HTTP/1.1 304 Not Modified"));
                }
            }
            die(
    ob_gzhandler($this->buffer1));
        }
    }

    ?>
    Last edited by bokeh; 02-18-2007 at 04:51 AM. Reason: To tidy up code!

  7. #7
    Join Date
    Dec 2006
    Location
    Escaz˙ (Costa Rica) and Mallorca (Spain)
    Posts
    3,234
    Perhaps not as professional, but yes, in that direction...

  8. #8
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,742

  9. #9
    Join Date
    Dec 2006
    Location
    Escaz˙ (Costa Rica) and Mallorca (Spain)
    Posts
    3,234
    Responding to your question: Something like this?

    Yes, something like this - I wouldn't have done as professionally, but it would've have been in that general direction...

  10. #10
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,742
    Ok, the class above was for caching internal files and I didn't read the question properly. Now I have read it here is a function to cache external URIs locally.
    PHP Code:
    <?php

    function CacheUriLocally($URI$CachePath$expires)
    {
        
    /*******************************************************
        
        FUNCTION NAME:
        CacheUriLocally
        
        AUTHOR:
        bokeh
        
        THREAD:
        http://webdeveloper.com/forum/showthread.php?t=138529
        
        PURPOSE:
        To cache a local copy of any URI.
        
        DESCRIPTION:
        string CacheUriLocally( string URI, string CachePath, int expires  )
        
        INPUTS:
        $URI is the full URI of the remote resource including 
        the scheme. $CachePath is an absolute or relative path 
        to the cache folder and must include a trailing slash. 
        $expires is the max age in seconds before the cached 
        data is considered stale.
        
        RETURN VALUE:
        Returns the URI output in a string
        
        NOTES:
        1) If you're opening a URI with special characters, such 
        as spaces, you need to encode the URI with urlencode().
        
        2) Be certain this script has sufficient permission to 
        read from and write to the cache directory.
        
        *********************************************************/
        
        
    if((file_exists($filename $CachePath md5($URI))) 
        and (
    filemtime($filename) > (time() - $expires)))
        {
            return 
    file_get_contents($filename);
        }
        
    $fp fopen($filename'w');
        
    fwrite($fp$rtn file_get_contents($URI));
        
    fclose($fp);
        return 
    $rtn;
    }

    echo 
    CacheUriLocally('http://www.google.com/''cache/'3600);

    ?>
    Last edited by bokeh; 02-18-2007 at 05:43 AM.

  11. #11
    Join Date
    Mar 2004
    Posts
    121
    Thank you all. This is perfect.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles