Over a million developers have joined DZone.
Platinum Partner

Encode Email Addresses With PHP

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

Spam bots will crawl your pages exactly the same way Search Engines crawls your pages, but while Search Engines are crawling to index your content, spam bots are crawling to find certain information.

One of the most common bits of data they are searching for are email addresses, this is because they can store these email addresses in a list and send out spam emails.

Displaying your email address on your web page makes it very easy for your visitors to store this and send you email, but you will need to get around the spam bot problem to do this you will need to HTML encode your email address.

While encoding your email address will make it display correctly in the browser in the source code the email address will be encoded so that spam bots can not read the email.

Below is a PHP code snippet which will allow you to pass in an email address and encode it so that you can display the email address on your website. This uses the PHP function ord() to return an ASCII value for the character used in the email.

 * Encode an email address to display on your website
function encode_email_address( $email ) {
     $output = '';
     for ($i = 0; $i < strlen($email); $i++)
          $output .= '&#'.ord($email[$i]).';';
     return $output;

To use in on your page all you have to do is pass in a parameter and it will return the encoded email you can now use on your website.

$encodedEmail = encode_email_address( 'example@domain.com' );
printf('<a href="mailto:%s">%s</a>', $encodedEmail, $encodedEmail);

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Paul Underwood , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}