Topic: Cache output of extern.php, a little help?
Updated: Simplified cache check a little.
I was trying to get my own little PunBB based portal working (yes, I like re-inventing the wheel ) and now I have a few questions about performance.
The thing is, I wanted to use extern.php on the page to display the latest 15 active topics. That part is all easy and good, but what I noticed was that this method isn't exactly the fastest way of doing things. There was a noticeable delay when refreshing the page, seeing as the script had to do a new SQL query.
I came to the conclusion that a system that kept the result in cache, for say 5min (put the expire time to low, and script would be useless), would be easier on the server. I came up with a pretty simple solution, but I want to ask if there are any even faster ways of doing this. Also, as I'm not the best PHP coder in the world (that's putting it mildly ), I'm sure there are better ways if working with arrays and the if statements.
Here's what I got so far (don't worry about the static links etc., that's just temporarily until my admin plugin is done):
<?php
$extern_url = 'http://beta.tasarinan.com/'; // Full url to folder containing extern.php. Trailing slash required!
$s_cache = PUN_ROOT.'cache/sidebar.html'; // Sidebar cache file. Must be writable!
$age = '300'; // Max cache age in seconds (300sec = 5min)
// sidebar cache generator
if (!file_exists($s_cache) || (time()-filemtime($s_cache) > $age)) {
// Generate new cache because the old one doesn't exist, or is outdated!
$tmp_php = file($extern_url.'extern.php?action=active') or die('Unable to fetch info from extern.php!');
$fh = @fopen($s_cache, 'wb');
foreach ($tmp_php as $tmp) {
fwrite($fh, $tmp) or die('Could not write to cache file');
}
fclose($fh);
}
?>
<h2 id="sidebar_h2_top">Navigation</h2>
<div class="box">
<div class="inbox">
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
<li><a href="#">Link 5</a></li>
</ul>
<h2>Active topics</h2>
<ul>
<?php
@(include($s_cache)) or die('Error fetching cache. Please check your configuration.');
?>
</ul>
</div>
</div>
If anyone want to test it, just change the variables at the top (script works on both linux and windows systems).
This way of doing it is a lot faster (on my server) than using just SQL, but as I said, I'm sure those of you more familiar with PHP can optimize it even further