ComputersGeneralLinuxProgrammingWeb Design

PHP Script to redirect and log connections

One thing that I’ve been wanting to do is to monitor outgoing links from a web site. It’s nice to know what links your visitors are clicking on, and if used for adverts could be essential to collecting revenue.

I’ve therefore created the following short PHP script. This has a redierct.ini file which should contain a list of shortnames to fullnames.

e.g. redirect.ini

Then the following named redirect.php
// Turn off error messages which may cause this to fail

// Default url if we don’t get a match
$url = ‘’;
$sitesfile = ‘redirect.ini’;
$logfile = ‘redirect.log’;

// Load the list of valid sites / urls
$listsites = parse_ini_file($sitesfile);

$site = trim($_GET[site]);
if (!empty($site))
if (!empty ($listsites[$site])) {$url=$listsites[$site];}
else $site = “Error-$site”;

// Log the entry – no error checking, other than don’t try and write if we can’t open
// we still want to redirect even if logging fails – e.g. to site home page
if ($fp = fopen ($logfile, ‘a’))
fwrite ($fp, date(“Ymd H:i:s”).” $site\n”);
fclose ($fp);

header( ‘Location: ‘.$url );


Whenever someone goes to /redirect.php?site=watkissonline then they will be redirect to, and details are logged into the redirect.log file.

This is how it works.

First error messages are turned off. If these are left on then any errors later will be sent to the browser, and the Location entry will no longer be the first value returned.

The entire ini file is loaded into a single hash called $listsites.
The parameter passed on the url is stored in $site.
If there is an entry in the $listsites hash for $site then that is used as the url. If not then we keep the default entry, but rename the entry in $site to Error-sitename, so that we log it as an error.

The entry is then written to a log before sending a redirect to the visitors browser.

There is not much error checking in this script which you may want to expand further. The error messages have been turned off to prevent errors from stopping the redirect. Any errors should result in the user going to the sites homepage (or whatever is set as the initial $url value).