Dynamically watching your web site via a PHP wrapper
Archive - Originally posted on "The Horse's Mouth" - 2010-05-21 07:36:16 - Graham EllisOn our web site, we "wrap" all of our pages in a PHP shell, which allows us to reference extra information easily within any of our pages, provide up to date course and hotel data on every page, and keep a dynamic log of current visitors in a database. The wrapper is applied through Apache http server (mod_rewrite), passing in the name of the page that's been called as a parameter to the wrapper script. Here are the "key" lines from various files:
From our web server configuration:
RewriteRule ^(.*)\.htm wrap.php?page=&%{QUERY_STRING}
From the wrapper URL page:
include ("$_SERVER[DOCUMENT_ROOT]/../afdr/wrapname.php");
And from the page that's included to run the real page:
$status = eval (" ?>$inclusion<?php ");
Once those preliminaries have been set up, we can start using our extra level of control - we open our database connection and log the access, for example:
$logit = "INSERT INTO recent (tstamp, remoteaddr,
calledfor, prevpage, serverhost, uagent) values (".
$nowsec . ", ".
"\"$rip\", ".
"\"$wanted\", ".
"\"$whence\", ".
"\"$server\", ".
"\"$ua\") ";
@mysql_query($logit);
and a further query on the same table causes each newly logged record to (additionally) delete any records over 15 minutes old.
What do we do with that extra data? We have a page which we describes as our "Traffic Watch" - see [here] - which gives us a snapshot of how the server is running (when staff are logged in, they are give far more data!), for example. And we can (and do) also use the script to watch for high traffic levels from an individual IP address.
On yesterday's PHP course, I wrote an example showing how PHP makes use of MySQL tables, using this data. See [source] and [run it]. This page lets me see which pages have been called up recently, with the most popular ones first - a very useful monitoring tool for administrators and for the SEO (Search Engine Optimisation) team.
Although I wrote the new example on the PHP programming course, the more advanced setup of the table - with mod_rewrite, etc, is beyond those few days, and it's something that we cover on our PHP Techniques Workshop. Web server setup (if you're going to be an administrator) is covered on Linux Web Server or if you need to learn a bit of Linux too, on Deploying LAMP.
P.S. You'll see from the source code that I've eliminated certain URL patterns from the live demonstration. These days, I'm afraid, there are a number of automated scripts that attack web sites - either to spread viral infection, or to inject their content via security holes into your site. Such accesses just "bounce" off our server, but they are logged; I have eliminated them from the report in the sample program to starve them of the oxygen or publicity.