geekblog.info

/ 10 posts / 2 comments / feed / comments feed

Dive Into Python: Python from novice to pro

Today I put the finishing touches on the Dive Into Python mirror over at http://diveintopython.geekblog.info .

I decided that rather than editing the source of every file to include my own custom Google search, I'd use apache mod-rewrite and php to replace relevant code on the fly and cache it. It is really simple, but does the job quite well.


The PHP Code:

// Send content type
header('Content-type: text/html');
 
// Check if a cached version is available
// If it is, print and die
$cachename = str_replace('/','_',$_REQUEST['FILE']);
if (file_exists('cache/'.$cachename))
{
	print file_get_contents('cache/'.$cachename);
	exit();
}
 
// Get the file we're asking for
$realHTML = file_get_contents($_REQUEST['FILE']);
 
// Ads
$ads = file_get_contents('inc/ads');
// Replace SSI with real ads
$shtml = '<!--#include virtual="/inc/ads" -->';
$realHTML = str_replace($shtml, $ads, $realHTML);
 
// Proudly Hosted By
$hosted = "
<p class="Footer" style="border-top: medium none; margin-bottom: 8px"><u>Dive Into Python</u> by Mark Pilgrim is proudly mirrored by <a href="http://geekblog.info/">GeekBlog.info</a>";
$body = "";
$realHTML = preg_replace("/$body/i", $hosted, $realHTML);
 
// Replace the default Custom Google Search
$oldSearch = addcslashes('
<form id="search" method="get" action="http://www.google.com/custom">\s+
 
<label for="q" accesskey="4">Find: </label>
<input id="q" name="q" size="20" maxlength="255" value=" " type="text" />
<input value="Search" type="submit" />
<input name="cof" value="LW:752;L:http://diveintopython.org/images/diveintopython.png;LH:42;AH:left;GL:0;AWFID:3ced2bb1f7f1b212;" type="hidden" />
<input name="domains" value="diveintopython.org" type="hidden" />
<input name="sitesearch" value="diveintopython.org" type="hidden" />
 
\s+</form>
 
',"/");
 
$newSearch = '
<!-- Google CSE Search Box Begins  -->
<form action="http://www.google.com/cse" id="searchbox_004948342960141248740:vdxqp1bv-tm">
<input name="cx" value="004948342960141248740:vdxqp1bv-tm" type="hidden" />
<input name="q" size="25" type="text" />
<input name="sa" value="Search" type="submit" />
</form>
 
<script src="http://www.google.com/coop/cse/brand?form=searchbox_004948342960141248740%3Avdxqp1bv-tm&amp;lang=en" type="text/javascript"></script>
<!-- Google CSE Search Box Ends -->
';
 
$realHTML = preg_replace("/$oldSearch/i", $newSearch, $realHTML);
 
// Create a cached version
$cache = fopen("cache/".$cachename, "w");
fwrite($cache, $realHTML);
fclose($cache);
 
// print and die
print $realHTML;
exit();
 

The Apache Code (.htaccess):

<ifmodule>
RewriteEngine On
RewriteBase /
 
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule ^(.+\.html)$ /hostedby.php?FILE=$1 [nc,qsa,l]
</ifmodule>
 

Head on over to Dive Into Python to check it out.

No comments

Leave a comment