Super simple page caching
When your project isn’t based on a CMS or framework, it can be a good idea to implement a simple caching system on your pages. The following code snippet is very simple, but works well for small websites.
`01.<?php`
`02.// define the path and name of cached file`
`03. $cachefile = 'cached-files/'.date('M-d-Y').'.php';`
`04.// define how long we want to keep the file in seconds. I set mine to 5 hours.`
`05. $cachetime = 18000;`
`06.// Check if the cached file is still fresh. If it is, serve it up and exit.`
`07.if (file_exists( $cachefile ) && time() - $cachetime < filemtime( $cachefile )) {`
`08.include( $cachefile );`
`09.exit;`
`10.}`
`11.// if there is either no file OR the file to too old, render the page and capture the HTML.`
`12.ob_start();`
`13.?>`
`14.<html>`
`15.output all your html here.`
`16.</html>`
`17.<?php`
`18.// We're done! Save the cached content to a file`
`19. $fp = fopen( $cachefile , 'w');`
`20.fwrite( $fp , ob_get_contents());`
`21.fclose( $fp );`
`22.// finally send browser output`
`23.ob_end_flush();`
`24.?>`
» Credit: Wes Bos
Type::snippet
Origin:: 10 super useful PHP snippets - CatsWhoCode.com
Language:: PHP