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

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.

Advertisements
Explore posts in the same categories: Computers, Development, Programming, Technical solutions

Tags: , , ,

You can comment below, or link to this permanent URL from your own site.

2 Comments on “PHP function for obfuscating e-mail addresses and phone numbers using Javascript.”

  1. Fritz Says:

    Latin characters like å,ä,ö works for me if the text is encoded in ANSI, UTF-8 otherwise output garbage (encoding failure). There is a workaround for that, just add these two lines in the beginning of the function:

    if(mb_detect_encoding($text, ‘UTF-8’, true))
    $text = utf8_decode($text);

    Works with ANSI and UTF-8 encoded files for me now. Happy coding!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s