I have varying mailto: email address on my site which are now being hit with various harvesters and subsequently I'm being spammed.

Can anyone assist me in creating some PHP code for the following:

<a href="mailto:info@company.com">info@company.com</a>

To prevent the address from being harvested and equally can I use this script on various email address displayed on the site?

Thanks

Accepted Answer

The best solution that I've found is to use a bit of javascript. You call a function, passing in the address, and it will print out the link for you. Since most bots don't process javascript, this should work for a majority of cases:

<script type='text/javascript'>
    function email(name, domain, withlink) {
        var addr = name + '@' + domain;
        if(withlink) {
            document.write('<a href="mailto:' + addr + '">' + addr + '</a>');
        } else {
            document.write(addr);
        }
    }
</script>

And then, when you want to print an email address on the site:

<script>email('myuser', 'mydomain');</script>

If you want it to make it a clickable link:

<script>email('myuser', 'mydomain', true);</script>

Note: This is untested, but it should work. There are also more advanced techniques, which some of the other answers touch on, but most of them build off of a base like this.

Written by Alex Vidal
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki