Looking for a php only email address obfuscator function
Asked Answered
T

6

11

Is there a php only email address obfuscator function? Most of the ones found on the web are a mix of JS and PHP.

Thornberry answered 25/9, 2012 at 23:6 Comment(1)
you mean a captcha that you need to fill before the real email address is sent to you? ;)Manganous
T
18

Here are a couple of functions I use.

First one obfuscates email address using html character codes:

function getObfuscatedEmailAddress($email)
{
    $alwaysEncode = array('.', ':', '@');

    $result = '';

    // Encode string using oct and hex character codes
    for ($i = 0; $i < strlen($email); $i++) {
        // Encode 25% of characters including several that always should be encoded
        if (in_array($email[$i], $alwaysEncode) || mt_rand(1, 100) < 25) {
            if (mt_rand(0, 1)) {
                $result .= '&#' . ord($email[$i]) . ';';
            } else {
                $result .= '&#x' . dechex(ord($email[$i])) . ';';
            }
        } else {
            $result .= $email[$i];
        }
    }

    return $result;
}

Example:

echo getObfuscatedEmailAddress('[email protected]');
-->
firstn&#x61;m&#x65;&#x2e;la&#115;t-name&#x40;examp&#108;e&#46;&#x63;om

Second one will return link where email address is both html and url encoded:

function getObfuscatedEmailLink($email, $params = array())
{
    if (!is_array($params)) {
        $params = array();
    }

    // Tell search engines to ignore obfuscated uri
    if (!isset($params['rel'])) {
        $params['rel'] = 'nofollow';
    }

    $neverEncode = array('.', '@', '+'); // Don't encode those as not fully supported by IE & Chrome

    $urlEncodedEmail = '';
    for ($i = 0; $i < strlen($email); $i++) {
        // Encode 25% of characters
        if (!in_array($email[$i], $neverEncode) && mt_rand(1, 100) < 25) {
            $charCode = ord($email[$i]);
            $urlEncodedEmail .= '%';
            $urlEncodedEmail .= dechex(($charCode >> 4) & 0xF);
            $urlEncodedEmail .= dechex($charCode & 0xF);
        } else {
            $urlEncodedEmail .= $email[$i];
        }
    }

    $obfuscatedEmail = getObfuscatedEmailAddress($email);
    $obfuscatedEmailUrl = getObfuscatedEmailAddress('mailto:' . $urlEncodedEmail);

    $link = '<a href="' . $obfuscatedEmailUrl . '"';
    foreach ($params as $param => $value) {
        $link .= ' ' . $param . '="' . htmlspecialchars($value). '"';
    }
    $link .= '>' . $obfuscatedEmail . '</a>';

    return $link;
}

Example:

echo getObfuscatedEmailLink('[email protected]');
-->
<a href="mailt&#111;&#58;%66i&#37;72stna%&#54;d&#x65;&#46;&#37;6c&#x25;6&#x31;st&#x2d;name&#64;&#101;&#x78;&#x61;mple&#46;co&#109;" rel="nofollow">f&#x69;&#114;s&#x74;na&#109;e&#x2e;&#108;a&#x73;t-name&#64;e&#x78;ample&#46;co&#109;</a>
Thornberry answered 25/9, 2012 at 23:6 Comment(3)
Interesting approach +1. But it might have some compatibilty issues.Skink
I haven't tested it in Safari and mobile browsers. FF, IE, Chrome are good.Thornberry
I like this approach. Will give it a shot and see if I get any spam.Toplevel
B
14

My fav:

Markup + PHP

<span class="rev"><?php echo strrev($email); ?> </span>

CSS

.rev{
    direction: rtl;
    unicode-bidi: bidi-override;
}

Fiddle

Bernardobernarr answered 25/9, 2012 at 23:20 Comment(5)
Brilliant! Any idea how this holds up when copy/pasting emails?Kamalakamaria
@AakilFernandes see fiddle : ((Bernardobernarr
Note that this method is far too easy reverse-engineered: if (email.indexOf('.') < email.indexOf('@')) email.reverse()Pita
How is this for accessibility?Lenni
@AakilFernandes moc.elpmaxe@olleh - so it's not a fit solution for copying data purposes.Talbot
B
3

Here's one with type-hinting.

Just call it with $this->obfuscateEmail($email);

/**
 * @param string $email
 * @return string
 */
private function obfuscateEmail(string $email): string
{
    $em = explode("@", $email);
    $name = implode(array_slice($em, 0, count($em) - 1), '@');
    $len = floor(strlen($name) / 2);

    return substr($name, 0, $len) . str_repeat('*', $len) . "@" . end($em);
}
Bonnibelle answered 4/4, 2017 at 3:2 Comment(1)
Note that the implode function's arguments should be reversed since PHP 8 : $name = implode('@', array_slice($em, 0, count($em) - 1));Pickett
C
2

Here is one more way which is quite tight and does not cause errors with https://validator.w3.org

function obfuscate($email){
$encoded_email = '';
for ($a = 0,$b = strlen($email);$a < $b;$a++)
{
    $encoded_email .= '&#'.(mt_rand(0,1) == 0  ? 'x'.dechex(ord($email[$a])) : ord($email[$a])) . ';';
}
return $encoded_email;}

Then to add to the page use:

<a href="mailto:<?= obfuscate(CONTACT_EMAIL.'?subject=Hello!') ?>"><?= CONTACT_EMAIL ?></a>
Caterpillar answered 25/11, 2018 at 23:46 Comment(0)
A
2

Some of these examples listed here are great, but I went with the WordPress antispambot() function, which is below for convenience:

function antispambot( $email_address, $hex_encoding = 0 ) {
    $email_no_spam_address = '';
    for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
        $j = rand( 0, 1 + $hex_encoding );
        if ( 0 == $j ) {
            $email_no_spam_address .= '&#' . ord( $email_address[ $i ] ) . ';';
        } elseif ( 1 == $j ) {
            $email_no_spam_address .= $email_address[ $i ];
        } elseif ( 2 == $j ) {
            $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[ $i ] ) ), 2 );
        }
    }

    return str_replace( '@', '&#64;', $email_no_spam_address );
}

function zeroise( $number, $threshold ) {
    return sprintf( '%0' . $threshold . 's', $number );
}

See WordPress for more details.

Aggrade answered 3/1, 2023 at 1:20 Comment(0)
A
0

Here an alternative way in case there is one character before host:

/**
* @param string $email
* @return string
*/

private function obfuscateEmail($email)
{
    $em   = explode("@", $email);

    $name = implode(array_slice($em, 0, count($em)-1), '@');

    if(strlen($name)==1){
        return   '*'.'@'.end($em);
    }

    $len  = floor(strlen($name)/2);

    return substr($name,0, $len) . str_repeat('*', $len) . "@" . end($em);
}
Aalst answered 9/8, 2017 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.