WordPress Code Snippets

A fresh mix of code snippets and tutorials

Spamless email links with PHP and jQuery

58

Couple of quick snippets for you today.. here’s how to display spamless email links on your web pages using either PHP or jQuery.

Spamless email links with PHP

Here is the PHP code:

<?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>';
} ?>

Spamless email links with jQuery

Here is the JavaScript/jQuery code:

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);

Check out more WP-Mix techniques for securing email forms:


Show Support

Like our new Facebook Page to show support!