Page next

Code Snippets

  • PHP/JavaScript Spambot protection

    Normal mailto-links often gets harvested by Spambots. To avoid this there exists already many techniques but several of them disable the functionality to click on the link and requires the user to copy the email address or even delete parts out of it.

    This little PHP scripts scrambles a text in Javascript which displays the text correctly when the browser renders the page so the user can still click on the link.

    The PHP Script:
    <html> <head> <title>Scan this, Spambot</title> </head> <body> <h1>Scan this, Spambot</h1> <form method="get" action=""> Email: <input type="text" name="email"><br> <input type="submit" value="Fire!"> </form> <?php if (isset($_GET['email'])) { print getJSCryptedString('<a href="mailto:'.$_GET['email'].'">'.$_GET['email'].'</a>'); } /** * Function to encrypt a text which will be decrypted * by the browsers Javascript engine. * Basically used against spambots. * @param string $text The text to encrypt * @return string */ function getJSCryptedString($text) { $len = strlen($text); $hash='v'.md5($text.rand(1,50)); $compl = getRandomString($len); $enc = getEncString($text,$compl); $ret = redoJS($hash,$enc,$compl); return '<script language="javascript">'.$ret.'</script>'; } function getRandomString($length) { $ret = array(); $possible = "0123456789bcdfghjkmnpqrstvwxyz". "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $i = 0; while ($i < $length) { $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); $ret[] = ord($char); $i++; } return $ret; } function getEncString($email, $compl) { $len = strlen($email); $ret = array(); for ($i=0;$i<strlen($email);$i++) { $ret[] = (ord(substr($email,$i,1)) ^ $compl[$i]); } return $ret; } function redoJS($h,$enc,$compl) { $ret = ''; $ret.= 'var '.$h.'1 = "'.implode('.',$enc).'";'; $ret.= 'var '.$h.'2 = "'.implode('.',$compl).'";'; $ret.= 'var '.$h.'4 = new Array();'; $ret.= 'var '.$h.'5 = new Array();'; $ret.= $h.'4 = '.$h.'1.split(".");'; $ret.= $h.'5 = '.$h.'2.split(".");'; $ret.= 'var ret = "";'; $ret.= 'var '.$h.'3 = '.$h.'1.length;'; $ret.= 'for(i=0;i<'.$h.'3;i++){'; $ret.= 'ret+=String.fromCharCode('.$h.'5[i] ^ '.$h.'4[i]);'; $ret.= '}'; $ret.= 'document.write(ret);'; return $ret; } ?> </body> </html>

Page next