Hide Your Email Addy with PHP

I came across this PHP Function while doing my morning reading, and thought I would share with others. I have not tried this method out, as I am a big fan of contact forms.

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

Use this PHP code where you would normally place your email:

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

This is the generated HTML code that the bots will see instead of the actual email addy and this is what your visitors will see if they "view Source":

<span id="e282283765">[javascript protected email address]</span>
<script type="text/javascript">// <![CDATA[
eval("var a="y4OTdF+6pU1ms8hCDbaKM.AENWLzVPq@QZ7SlxvwkJYInGHRr_tc9uf2BoXg053-eji";var b=a.split("").sort().join("");var c="0Gg080Gg0OI2u";var d="";for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));document.getElementById("e282283765").innerHTML="<a href="mailto:"+d+"">"+d+"</a>"")
// ]]></script>

The PHP Function Code

<?php 
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;
}
?>

Easy!