Quick JavaScript email obfuscation
Posted on April 5th, 2004 in Code Repository | 7 Comments »
There are many methods to quickly obscure an email address from spam harvesters, this approach relies on the fact that most email harvesters won’t understand JavaScript.
/**
* Obfuscate an email address
*
* @author Aidan Lister <aidan@php.net>
* @version 1.1.0
* @link http://aidanlister.com/2004/04/quick-javascript-email-obfuscation/
* @param string $email E-mail
* @param string $text Text
*/
function mail_obfuscate($email, $text = '')
{
// Default text
if (empty($text)) {
$text = $email;
}
// Create string
$string = sprintf('document.write(\'<a href="mailto:%s">%s</a>\');',
htmlspecialchars($email),
htmlspecialchars($text));
// Encode
for ($encode = '', $i = 0; $i < strlen($string); $i++) {
$encode .= '%' . bin2hex($string[$i]);
}
// Javascript
$javascript = '<script language="javascript">eval(unescape(\'' . $encode . '\'))</script>';
return $javascript;
}
A quick example:
echo mail_obfuscate('aidan@php.net');
Would result in:
<script language="javascript">eval(unescape('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%61%69%64%61%6e%40%70%68%70%2e%6e%65%74%22%3e%61%69%64%61%6e%40%70%68%70%2e%6e%65%74%3c%2f%61%3e%27%29%3b'))</script>
As you can see, the output no longer remotely resembles an email address and is very unlikely to get picked up by a spam harvester.
7 Responses
very nice;) thnx a lot for this useful code
This is losely based on the obfuscator in Smarty, and is the function used to obfuscate the emails in the comments on this site.
i love this one …. I HATE spammers …
GOOD WORK MEN!.
NICE NICE NICE
with this modification you can set class attributes or id for CSS support.
old: function mail_obfuscate($email, $text = ”)
new: function mail_obfuscate($email, $text = ”, $plus_params=”)
old: $string = sprintf(‘document.write(\’<a href=”mailto:%s”>%s</a>\’);’,
htmlspecialchars($email),
htmlspecialchars($text)
new: $string = sprintf(‘document.write(\’<a href=”mailto:%s” %s>%s</a>\’);’,
htmlspecialchars($email),
$plus_params,
htmlspecialchars($text)
usage: mail_obfuscate(“info@riaevolution.com”, $text = ‘info@riaevolution.com’, ‘class=”link_content_footer”‘);
Excelent function! thank you for sharing your code
@Aidan
I have developed a solution for just such a need. My free (beer + speech) script called PrivateDaddy walks over all the mailto links in your site and replaces them automatically. The script is unobtrusive and also works for browsers with JavaScript disabled. Best of all it doesn’t get in the way – just one line of code in header.php (or whatever header file you use) and your entire site is covered.
Hope you find this shameless plug useful
Cheers,
Andy
@Andy
Forgot – the link is http://www.privatedaddy.com/