esafwan esafwan - 4 months ago 19
PHP Question

Tracking email with PHP and image

I have seen the service like spypig.com placing a small image in the email and tracking when it is opened and from where. They track city, country, IP address etc. How is this done?


  1. How do we know when the mail is opened? And how is the image
    generated?

  2. How is the IP address detected and how is it possible to know location from
    it?


Answer

Basically, in the HTML body of your email, there will be an <img> tag that would look like this :

<img src="http://www.yoursite.com/tracker.php?id=123456" alt="" />

When someone reads his mail, with images enabled, the email-client will send a request to tracker.php, to load the image, passing it id=123456 as a parameter.


This tracker.php script will be on your server, and, when called, it will :

  • Check the id parameter,
  • Use it to find to which email address it corresponds -- when generating the email for each one of your subscribers, you'll have generated an id different for each e-mail.
  • Do some stuff -- like log "email 123456 has been opened", and some additional informations
  • return the content of a small image ; like a 1x1 transparent gif.


The tracker.php script knows from which IP address it's been called -- like any other PHP script :

$ipAddress = $_SERVER['REMOTE_ADDR'];

And, starting from this IP address, you can use a geolocation service to find out from where in the world the email has been opened.
As a couple of examples, you could take a look at MaxMind, or IPInfoDB

As you know that id=123456 corresponds to one specific email address, this allows to find out where each one of your subscribers are.