Posted tagged ‘ruby’

PHP function for obfuscating e-mail addresses and phone numbers using Javascript.

04/10/2011

Update 2012-12-23

The technique below is now available as a WordPress plugin. Check out the Email Obfuscate Shortcode plugin!

Here’s a short snippet that I have been using in various PHP projects to protect e-mail addresses and phone numbers against being harvested for spam purposes. It uses Javascript to scramble some text and output it as a self-contained piece of Javascript. It’s compatible with all major browsers (and IE5.5 and up). The idea is based on this ruby snippet, so head over there if you want to read more about the way it works!

safe_text() snippet

function safe_text($text)
{
    if(mb_detect_encoding($text, 'UTF-8', true))
        $text = utf8_decode($text);

    $ret = '
<script type="text/javascript">// <![CDATA[
                    var t=[
                ';
    $chars = str_split($text);

    $enc[] = rand(0,255);

    foreach($chars as $char)
    {
        $enc[] = ord($char)-$enc[sizeof($enc)-1];
    }

    $ret .= join(',',$enc);
    $ret .= '
                ]; for (var i=1; i<t.length; i++) { document.write(String.fromCharCode(t[i]+t[i-1])); }
// ]]></script>';

    return $ret;
}

To output the Javascript anywhere (it’s entirely self-contained), simply run:

echo safe_text('bob@examplecorp.com');

Update: Thanks to Fredrik for a fix that makes this function multibyte safe! It now also works with special characters like å,ä,ö and similar.