email

Encode Email Address with PHP and Javascript

Posted on: June 21st, 2012 by taff No Comments

 

Posting your email address anywhere on the web without encoding it in some way is not something you should do unless you want plenty of spam. In my opinion using email "encryption" techniques like person[at]domain[dot]com aren't going to stop a lot of bots either. If they are smart enough to build a crawler looking for email addresses with regular expressions, they are also going to be looking for [at]. If you have PHP and Javascript possibilities, you can protect yourself to a large extent with this useful snippet to encode mailto addresses.
This is a little PHP script that I use a lot.

<?php
function encryptAddress($address){
	$output="<script type="text/javascript">";
	$output.="var listOfEncryptedLetters=[";
	for($i=0;$i<strlen($address);$i++){
		$output.= ord(substr($address,$i,1)).",";
	}
	$output = substr($output, 0, -1); 
	$output.= "&#93;n";
	$output.="
	var newName='';
	for (var i=0; i<listOfEncryptedLetters.length; i++)
	 newName+=String.fromCharCode(listOfEncryptedLetters&#91;i&#93;)
	document.write('<a href="mailto:'+newName+'">'+newName+'</a>')
	</script>";
	return $output;
}
echo encryptAddress("info@test.html");
?>

Using a simple PHP loop, we consecutively convert each letter of the string passed to the function into it's equivalent ASCII value and add it to a Javascript array.

var listOfEncryptedLetters=[105,110,102,111,64,116,101,115,116,46,104,116,109,108]

The next step is to output our encrypted ASCII code as Javascript, with which we generate our anchor with a mailto:.
The output should look something like this now:

<script type="text/javascript">var listOfEncryptedLetters=[105,110,102,111,64,116,101,115,116,46,104,116,109,108]

	var newName='';
	for (var i=0; i<listOfEncryptedLetters.length; i++)
	 newName+=String.fromCharCode(listOfEncryptedLetters&#91;i&#93;)
	document.write('<a href="mailto:'+newName+'">'+newName+'</a>')
	</script>

Hope this helps. If you don't have PHP available but would like this script, holler and I'll throw up a form to automatically generate code so you can just copy and paste. I hope this script to encode your email address with javascript helps. I am not even sure if the crawlers do javascript so you may even get away with a document.write.