Skip to content

Email ASCII encode helper

Derek Jones edited this page Jul 4, 2012 · 4 revisions

For basic spam protection I did set up a helper that encodes email addresses in ASCII.

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Encodes (ASCII) email addresses for basic spam protection
 *
 * @access    public
 * @param    string - email address
 * @param    string
 * @param    bool
 * @param    string - name of css class
 * @return    string
 *
 * @author    Luckyfella73
 */

// ------------------------------------------------------------------------

/**
* Usage Exaples:
*
* returns pure email address ASCII encoded:
* echo (encode_email('[email protected]'));
*
* returns email address ASCII encoded with "mailto: link" and defined anchor text:
* echo (encode_email('[email protected]','John Doe',TRUE));
*
 * returns email address ASCII encoded with mailto: link, defined anchor text and css class for <a> tag:
 * echo (encode_email('[email protected]','John Doe',TRUE,'my-link-style'));
*/
if ( ! function_exists('encode_email'))
{
    function encode_email($email, $anchor_text = '', $mailto = FALSE, $css = '')
    {
        $email = trim($email);
        $anchor_text = trim($anchor_text);
        $css = trim($css);

        if ($email === '')
        {
            return '';
        }

        $email_encoded = '';
        for ($i=0; $i < strlen($email); $i++)
        {
            $email_encoded .= '&#'.ord(substr($email,$i)).';';
        }

        if ($anchor_text === '')
        {
            $anchor_text = $email_encoded;
        }

        if ($mailto === TRUE)
        {
            if (strlen($css) > 1)
            {
                $css = ' class="'.$css.'" ';
            }
            return '<a href="milto'.$email_encoded.'">'.$anchor_text.'</a>'. "\n";
        }
        else
        {
            return $email_encoded;
        }
    }
}

/* End of file email_encode_helper.php */
/* Location: ./system/application/helpers/email_encode_helper.php */
Clone this wiki locally