-
-
Save chrisamoore/2901513 to your computer and use it in GitHub Desktop.
Visitor tracking with PHP and Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
/** | |
* 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