This PHP function / jQuery plugin will create an obfuscated mailto link that will protect your email addresses from the spam bots that harvest the web. This is accomplished by:
This function will create an obfuscated mailto link that is only decoded when an actual user hovers over the link with their mouse and clicks on it.
$text | The anchor text. |
$to | The email address. |
$subject | The email's subject. |
$body | The email's body. This can include <br /> tags and newlines. |
Returns | Your obfuscated email link. |
Example | $html .= email_link('Spam me please', 'spam@email.ru', 'faster cheaper meds', "Hello friend,\n\nWe are please to offer..."); |
<?php function email_link ($text, $to, $subject='', $body='') { global $page; $page->link('jquery.nospam.js'); $page->jquery('$("a.nospam").nospam();'); $link = 'mailto:' . rawurlencode($to); $params = array(); $remove = array('&', '=', '?', '"'); if (!empty($subject)) $params[] = 'subject=' . rawurlencode(str_replace($remove, '', $subject)); if (!empty($body)) { $body = str_replace(array("\r\n", "\n", '<br />'), array("\n", '', '%0A'), nl2br($body)); $params[] = 'body=' . rawurlencode(str_replace($remove, '', $body)); } if (!empty($params)) $link .= '?' . implode('&', $params); $link = base64_encode($link); return '<a class="nospam" href="#" title="' . $link . '">' . $text . '</a>'; } ?>
function decode64 (input) { var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4 = ""; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) output = output + String.fromCharCode(chr2); if (enc4 != 64) output = output + String.fromCharCode(chr3); chr1 = chr2 = chr3 = enc1 = enc2 = enc3 = enc4 = ""; } return unescape(output); } (function($) { $.fn.nospam = function(){ return this.each(function(){ var href = $(this).attr("href"); var title = $(this).attr("title"); $(this).hover( function(){ $(this).attr({"href":decode64(title), "title":"Click to send email"}); }, function(){ $(this).attr({"href":"#", "title":title}); } ); }); }; })(jQuery);