Skip to content

Instantly share code, notes, and snippets.

@tzusman
Created November 25, 2011 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tzusman/1392976 to your computer and use it in GitHub Desktop.
Save tzusman/1392976 to your computer and use it in GitHub Desktop.
Visitor tracking with PHP and Redis
<?
/**
* Read about why this script was written at http://blog.toddzusman.com/post/13291374815/visitor-tracking-using-php-and-redis
*/
// I'm using Predis from https://github.com/nrk/predis
require '/path/to/predis/lib/Predis/Autoloader.php';
Predis\Autoloader::register();
$conf = array();
$conf['host'] = '127.0.0.1';
$conf['port'] = 6379;
$client = new Predis\Client( $conf );
function debug ( $msg ) {
if ( false )
printf( "%s <br />\n", $msg );
}
$host = 'tracking.toddzusman.com';
$hash = $_GET['hash'];
$day = floor( time()/86400 );
if ( array_key_exists('r',$_GET) || $_COOKIE['t'] == 'confirmed' ) {
debug( "Either we've already been redirected or the cookie is already confirmed, so mark this as a page view" );
$client->hincrby( 'pageviews:'.$hash, $day, 1 );
}
if ( isset($_COOKIE['t']) ) {
debug( 'The cookie has been set [t='.$_COOKIE['t'].']' );
if ( $_COOKIE['t'] == 'confirmed' ) {
debug( 'Cookie exists and was already confirmed, so do nothing' );
} else if ( array_key_exists('r',$_GET) ) {
debug( "We've already been redirected, so the browser CAN accept cookies" );
debug( "Setting cookie 't' to confirmed" );
setCookie( 't', 'confirmed', time()+1576800000, '/', $host, false );
debug( 'Incrementing the uniques' );
$client->hincrby( 'unique:'.$hash, $day, 1 );
} else {
debug( "Something fishy happened - the cookie is there but not confirmed, but we have't been redirected" );
}
} else {
debug( 'No cookie has been set' );
if ( array_key_exists('r',$_GET) ) {
debug( "We've already been redirected, so the browser CANNOT accept cookies" );
$client->hincrby( 'nocookie:'.$hash, $day, 1 );
} else {
debug( 'The cookie has not been attempted, so we need to set it and redirect' );
debug( "Setting cookie 't' to redirect" );
setCookie( 't', 'redirect', time()+1576800000, '/', $host, false );
header( 'Cache-Control: no-cache, must-revalidate' );
header( 'Expires: Fri, 9 Sep 1988 05:55:00 EST' );
header( 'Location: /?r=1&hash='.$hash, true, 302 );
exit;
}
}
header( 'Cache-Control: no-cache, must-revalidate' );
header( 'Expires: Fri, 9 Sep 1988 05:55:00 EST' );
header( 'Content-Type: image/gif' );
echo base64_decode( 'R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment