12-Sep-2020 : Web page logging

  • by

This is the oldest bit of PHP in my possession, based on something I found on the Web about ten years ago but tweaked by me over the years to suit my purposes.  It logs all accesses to a Web page with the date and time, the IP address of your visitor, and the address of the page being accessed.

Place the code in a file called something.php in a folder somewhere in the path where your Web site is installed, inserting any IP addresses you want excluded from being logged following the # don’t log my own activity comment, and in the same format.  Change the fopen() statement to point to the folder where you want your log files to be written, and create the folder.

Here’s the code:-

<?php
/**
* Records all page loads except my own IP addresses
*
*/
if (getenv (“HTTP_CLIENT_IP”))
$ip = getenv (“HTTP_CLIENT_IP”);
else
if (getenv (“HTTP_X_FORWARDED_FOR”))
$ip = getenv (“HTTP_X_FORWARDED_FOR”);
else
if (getenv (“REMOTE_ADDR”))
$ip = getenv (“REMOTE_ADDR”);
else
$ip = “UNKNOWN”;

$ip = str_pad ($ip , 15);
# pad to 15 chars so log file lines up nicely

# don’t log my own activity – remove the next line if you want to log yours
if ( str_replace(” “, “”, $ip) == “xxx.xx.xx.xxx” ) { return; }
if ( str_replace(” “, “”, $ip) == “yyy.y.yyy.yy” ) { return; }

$page = getenv (“HTTP_REFERER”);
# the page on your site which is accessed

date_default_timezone_set (“Europe/London”);
$logfilename = date (“Ymd”) . “.log”;
# choose your own filename – this makes 20200912.log
$fh = fopen (“./logs/$logfilename” , “a”);
# set your log file folder path here
fwrite ($fh , date (“Y/m/d H:i:s – “) . $ip . ” – ” . $page . “\n”);
fclose($fh);
return “”;
?>

I think even with limited experience you can probably see what it’s doing.

To test that it’s working okay, make sure your IP address isn’t in the exclusions list – insert an ‘X’ in it or comment out the entire line – then in your browser’s address bar, paste in or type the full URL of your PHP module: http://yourdomain.co.uk/yourpath/yourfilename.php (adjusting the bits in red italics to reflect your setup).  Now cPanel in to your Web space and navigate to your logs folder, then view the file with today’s date, or type it’s full URL into your browser”’s address bar: http://yourdomain.co.uk/yourpath/logs/20200912.log (adjusting the red bits), and it should appear on your screen.

Is it working?  Good!

You’re now ready to go – you just need to add some HTML which will call the PHP module from any page whose activity you want logged.  I reckon the place where you’ll have the most control over it (see footnote) is in a widget.  You can use an existing one or you can create a new one: if you decide on a new one, select Custom HTML (or your equivalent – my example is for WordPress).  I tend to tack it on to the end of things like page counters, visitor maps, Google Ads, etc, hidden away inside a zero-size <iframe> which doesn’t betray its presence.  Here’s the HTML I use:-

<iframe src=”http://yourdomain.co.uk/yourpath/yourfilename.php” width=”0″ height=”0″></iframe>

Footnote

You can do away with the <iframe> kludge if you have access directly to the PHP which generates your Web pages.  In WordPress these can be accessed:-

1.  Via your site’s Dashboard (Appearance > Theme Editor).  You will get a dire warning message the first time you try to do this, since damaging a theme’s PHP files will occasionally totally prevent a site from loading, and if this happens you won’t be able to get back in to your Dashboard to rectify the problem.  For this reason I’d recommend that you do not tinker with these files unless you know for sure that you can get back in via cPanel to restore the backup(s) you made beforehand.  (You did make a backup, didn’t you?  Yes, of course you did.)

Assuming you’ve chosen to make the changes via your Dashboard, you’ll be presented with a code edit window and a list of all the ‘template’ files you can customise down the right-hand side of the screen.  You should insert your PHP code into a template which is used to load every page you want logged, and this will usually be header.php or footer.php.  I’m not going to tell you exactly where in the file you should insert it since this will vary from theme to theme and you will need to be fairly sure you’re putting it somewhere sensible.  For example, if you insert it into an HMTL segment, you’ll need the <?php ?> wrapper; if you insert it into an existing piece of PHP, then you do without it.

Test your changes as described above, i.e. remove or comment out your IP address from the code, access your Web site via a browser, access a few pages, then take a look in your logs folder for the expected file using cPanel or display it using your Web browser as described above, and confirm that day’s log file has recorded your activity.

Eventually you may break your theme – in fact it’s almost a rite of passage – so it’s probably a good idea to check you can access your site via cPanel.  Do it now – don’t wait until your site’s down to find out you don’t have the password!

2.  Alternatively you can make the changes via cPanel (or equivalent).  Log in, open File Manager, and navigate to the location of your theme’s PHP files.  In WordPress this will be somewhere like /yourhomepath/public_html/wp/wp-content/themes/yourtheme/.  At this point make a backup of the any PHP file you wish to change.  Now make the changes (keeping a close eye on the little red x which indicates that you’ve made a syntax error – you can’t save a file with a syntax error, anyway), and click Save.  Don’t close the editor yet.

In a separate browser page, go to your site’s home page.  Did it load okay and does it look unusual in any way?  Check a selection of pages and posts just to make sure.  If anything does appear to have gone awry, you’ve probably disturbed the way your WordPress theme loads its content, and you’ll need to go back to cPanel and re-examine where you inserted the new code.  This why I suggested you keep your PHP editor open.  If you totally screw things up moving or removing your code, you’re best off restoring the backup copy you made.  (Even if your site’s completely down, this won’t affect your ability to use cPanel.)  I keep a copy of all the theme”s PHP files on my home PC just to be on the safe side.


Did you give that a try?  If so, please let me know how you got on.  Drop me a line via this contact form or email me.  I might not be able to help you fix anything but you can always rely on me for a bit of sympathy!