Simple PHP Script To Hide An Email Address In An Image

4th March 2008 - 3 minutes read time

Spam is a problem. You want to allow people who genuinely want to get in touch to see your email address, but doing this invariably leads to you getting thousands of spam emails.

One solution is to hide your email address in an image, but it can be a pain to create an image for every email address you need. A better solution is to use the PHP GD functions to create an image at runtime so that your email address is displayed, but is completely unreadable to spammers.

To to this you will need to create an image tag on your website, here is an example.

<img src="[email protected]" alt="Hidden Email" />

This calls the image.php file and passes a single parameter called text. This parameter is the email address you want to display, but it is written backwards. The script first turns the string around and then adds the string to an image. Because the script returns the correct header for an image type (Content-type: image/png) it will be displayed as an image on the browser.

if (isset($_GET['text'])) {
  // get string
  $text = $_GET['text'];
 } else {
  // set default
  $text = 'liame';
 };
 // reverse string
 $text = strrev($text);
 $textLength = strlen($text);
 $textHeight = 10;
 
 // create image handle
 $image = ImageCreate($textLength*($textHeight-1),20);
 
 // set colours
 $backgroundColour = ImageColorAllocate($image,255,255,255); // white
 $textColour = ImageColorAllocate($image,0,0,0); // black
 
 // set text
 ImageString($image,$textHeight,0,0,$text,$textColour);
 
 // set correct header	
 header('Content-type: image/png');
 
 // create image
 ImagePNG($image);

This is a fairly simple mechanism to create an image, and you will need to have the GD functions installed on your server or it will just return an error.

To further customise the look of the image you can change the colours stipulated in the variables $backgroundColour and $textColour to fit in with the colour scheme of your own site.

Add new comment

The content of this field is kept private and will not be shown publicly.