Visitor tracking image

I wrote a script in PHP to track visitors to my blog. This is just a proof of concept. It generates an image using the GD graphics library that displays text showing the visitor info and saves to a database. It uses PDO to save the hits to a MySQL database. The contents of the image are unimportant, as is the storage method.

Anyway, here’s the image:

You can view the results here.

And here’s the code:

# image hit counter


// db config info
// get visitor info from server
$ip_address = $_SERVER[‘REMOTE_ADDR’];
$referer = $_SERVER[‘HTTP_REFERER’];
$time_of_visit = time(); // not used — call NOW() in db insert because it’s already in MYSQL TIMESTAMP format

if (trim($referer) == “”)
$referer = “unknown”;

// use database to store visitor info
$pdo = new PDO(‘mysql:host=’ . $dbhost . ‘;dbname=’ . $dbname, $dbuser, $dbpass);

// add visitor info to database
$stmt = $pdo->prepare(“INSERT INTO visitors (ip_address, time_of_visit, referer) VALUES (:ip_address, NOW(), :referer)”);
$stmt->bindParam(“:ip_address”, $ip_address);
$stmt->bindParam(“:referer”, $referer);

// get visitor number from database
$query = $pdo->prepare(“SELECT count(*) FROM visitors”);
$count = $query->fetchColumn(0);
catch (Exception $e)
echo $e->getMessage();
exit (“db error, unable to create image”);

// create string with visitor info
$count_string = “You are visitor # ” . $count . “\r\n”;
$ip_string = “Your IP address is: ” . $ip_address . “\r\n”;
$referer_string = “You came from : ” . $referer . “\r\n”;

$visitor_info = $count_string . $ip_string . $referer_string;

// generate and dispay image to be included for tracking purposes
$img = imagecreate(1000, 300);
$bgcolor = imagecolorallocate($img, 255, 255, 255);
$fgcolor = imagecolorallocate($img, 0, 0, 0);

$r = imagestring($img, 5, 0, 0, $visitor_info, $fgcolor);
if ($img !== false)
header(“Content-type: image/jpeg”);
exit (“error creating image”);


I had 2 issues.

One is with GD createimagefromtext() — how can I create multiline text images? adding newline (\n) doesn’t work.

The other is with PDO — are you serious that there is on way to output the text of a prepared statement before (or after) executing for debugging purposes. I tried $stmt->debugDumpParams() but that just crashed my server.

2 thoughts on “Visitor tracking image

  1. In order to get PHP to process counter.jpg, create an .htaccess file that looks like this:

    <FilesMatch “counter\.gif$”>
    ForceType application/x-httpd-php

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s