Main menu:


Site search

Archives

RSS Arjen's Friendfeed

RSS Richard's del.icio.us links

RSS Maurits' Stumbled Items

PHP hide_email() function

What is it?

A PHP function to protect the E-mail address you publish on your website against bots or spiders that index or harvest E-mail addresses for sending you spam. It uses a substitution cipher with a different key for every page load.

How does it work?

PHP encrypts your E-mail address and generates the javascript that decrypts it. Most bots and spiders can’t execute javascript and that is what makes this work. A visitor of your web page will not notice that you used this script as long as he/she has javascript enabled. The visitor will see “[javascript protected email address]” in stead of the E-mail address if he/she has javascript disabled.

Example

<?php echo hide_email(’test@test.com’); ?>

This is the PHP code you write where you want the E-mail address on your web page.

test@test.com

This is what the E-mail address will look like for the visitor of your web page.

<span id="e478988720">[javascript protected email address]</span><script type="text/javascript">
/<![CDATA[/eval(”var a=\”Bdnf8Ov32X0GAMexiu-pERHYWQVj4JUmS9g@skbF7DZPqNI+TLy16toCca.lhwK_5zr\”
;var b=a.split(\”\”).sort().join(\”\”);var c=\”hNlhMhNlhnPCt\”;var d=\”\”;for(var e=0;e<c.length
;e++)d+=b.charAt(a.indexOf(c.charAt(e)));document.getElementById(\”e478988720\”).innerHTML=\”<a
href=\\”mailto:\”+d+\”\\”>\”+d+\”</a>\”")/]]>/</script>
This is the generated XHTML that the bot or spider will see instead of your E-mail address.

The code

The “hide_email()” PHP function is only 9 lines of code:

function hide_email($email)
{ $character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
$key = str_shuffle($character_set); $cipher_text = ''; $id = 'e'.rand(1,999999999);
for ($i=0;$i<strlen($email);$i+=1) $cipher_text.= $key[strpos($character_set,$email[$i])];
$script = 'var a="'.$key.'";var b=a.split("").sort().join("");var c="'.$cipher_text.'";var d="";';
$script.= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
$script.= 'document.getElementById("'.$id.'").innerHTML="<a href=\"mailto:"+d+"\">"+d+"</a>"';
$script = "eval(\"".str_replace(array("\",'"'),array("\\",'\"'), $script)."\")";
$script = '<script type="text/javascript">/<![CDATA[/’.$script.’/]]>/</script>’;
return ‘<span id=”‘.$id.’”>[javascript protected email address]</span>’.$script;
}
License: Public domain.

Maurits

Write a comment