Technology

HOWTO: Create a Graphical Counter with Metrics API

In my last HOWTO I showed how you can display your Metrics visit count in your WordPress or Drupal blog. While it does show the values off I thought I would show how you can make it a little more old school by displaying a graphical counter. As well as displaying your visit count it serves as a nice little advert for our Metrics service!

All the hard work has already been done in the last post, providing your PHP install includes support for GD you have everything you need and it is really very easy.

What we need to do is change the text that is output in the previous examples code to instead output an IMG tag referencing a new PHP script. This PHP script will return the generated image showing a Performancing logo and our visit count.

So last time we had the following:


print "

  • VISITS TODAY: $text
  • ";

    We need to replace this with:


    print "\"Visit";

    As you can see it outputs an IMG tag that references our new PHP, supplying the text we want to overlay as a URL parameter. Here is the code for graphic.php which you need to put in your web root along with your copy of background.png

    The first line tells your web browser that you are outputting a PNG image. This is important as otherwise the browser would not be able to interpret the binary data we are sending. This is also why you can not output the image as part of the plugin, you can not mix HTML and binary data in a single output.

    Next we accept the text string from the querystring parameter and create a new image in memory based on our background image.

    Drawing basic text over the image is as simple as choosing an RGB colour and supplying the image, font size, x and y coordinates, text and colour to the GD “imagestring” function.

    Finally we send the new modified image to the users browser and destroy our image from memory to clean up after ourselves.

    Told you it was easy, eh? Here is what the final thing looks like:

    Author: Chris Garrett

    Chris Garrett is a content marketing and blogging coach and co-author of the Problogger Book with Darren Rowse.

    4 thoughts on “HOWTO: Create a Graphical Counter with Metrics API

    1. As a good security practice, you don’t want to use user submitted info via the $_GET or $_POST array without validating and sanitizing it first. In this case, I’d suggest replacing the following

      , with a regular expression validation

      To make sure your script gets a string like ‘VISITS ‘;

    2. As chris is the first to admit, his graphical skills are only marginally better than mine, so if anyone wants to take this howto and produce a truly awesome looking counter widget, we’ll give credit and put it on the soon coming dedicated page for API widgets!

    Comments are closed.