Protecting Email Addresses Using ASCII Codes


In the browser, you just see an email link; however, the underlying HTML markup is indecipherable:

<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;
&#121;">Send mail</a>
Protecting Email Addresses
  function protectMail($s) {
    $result = '';
    $s = 'mailto:' . $s;
    for ($i = 0; $i < strlen($s); $i++) {
      $result .= '&#' . ord(substr($s, $i, 1)) .
    return $result;
  echo '<a href="' .
    protectMail('email@address.xy') .
    '">Send mail</a>';

However, take a look at figure: The email address is decoded correctly by the web browser, as can be seen in the status bar.

Machine beats man (when deciphering the email address).

Some special characters are difficult to use in strings because they are hard to enter using a keyboard. However, they all have an ASCII value. PHP offers two functions to deal with this:

  • chr() converts the ASCII code into the corresponding character

  • ord() returns the ASCII code for a character

This can be used to protect email addresses, for instance. Because spammers are writing software to search for certain patterns (email adresses) on web pages, this might help keep spam low. The trick is to use HTML character codes for email addresses, making it much harder for spambots to find email data.

The preceding code takes an email address (in the format email@address.xy) as a parameter and returns mailto:email@address.xybut converted into HTML entities. For instance, the m of mailto: has the ASCII code 109; therefore, $#109; stands for m. To do so, a for loop iterates through all characters in the string. To do so, the length of the string has to be determined, which can be done using strlen(). Then, a call to ord() calculates the ASCII code of each character, which is then used for the resulting HTML.

Of course, this does not offer a bulletproof protection; you might consider using alternative ways to obscure the email address, including a syntax such as email at address dot xy.