wpseek.com
A WordPress-centric search engine for devs and theme authors



antispambot › WordPress Function

Since0.71
Deprecatedn/a
antispambot ( $email_address, $hex_encoding = 0 )
Parameters: (2)
  • (string) $email_address Email address.
    Required: Yes
  • (int) $hex_encoding Optional. Set to 1 to enable hex encoding.
    Required: No
    Default:
Returns:
  • (string) Converted email address.
Defined at:
Codex:
Change Log:
  • 7.1.0

Obscures email addresses in HTML to prevent spam bots from harvesting them.

Typically this will randomly replace characters from the email address with HTML character references; however, when the hex encoding parameter is set, some characters will also be represented in their percent-encoded form. Because this function is randomized, the outputs for any given input may differ between calls. This helps diversify the ways the email addresses are obscured. When non-UTF-8 inputs are provided, any spans of invalid UTF-8 bytes will be passed through without any obfuscation. Example: $email = 'noreply@example.com'; $obscured = antispambot( $email ); $obscured === 'noreply@example.com'; // Hex-encoding also obscures characters with percent-encoding. $obscured = antispambot( $email, 1 ); $obscured === '%6eore%70l%79@%65x%61mple%2e%63%6fm'; // Non-UTF-8 characters are not obfuscated. "xFC" is Latin1 "ü". $obscured = antispambot( "bxFCcher@library.de" ); $obscured === 'b�cher@library.de'; $obscured === "bxFCcher@library.de"


Source

function antispambot( $email_address, $hex_encoding = 0 ) {
	$obfuscated     = '';
	$at             = 0;
	$end            = strlen( $email_address );
	$invalid_length = 0;

	while ( $at < $end ) {
		$was_at = $at;
		if (
			0 === _wp_scan_utf8( $email_address, $at, $invalid_length, null, 1 ) &&
			0 === $invalid_length
		) {
			break;
		}

		$character_length = $at - $was_at;

		if ( $character_length > 0 ) {
			$character = substr( $email_address, $was_at, $character_length );

			switch ( rand( 0, 1 + $hex_encoding ) ) {
				case 0:
					$code_point  = mb_ord( $character );
					$obfuscated .= "&#{$code_point};";
					break;

				case 1:
					$obfuscated .= $character;
					break;

				case 2:
					for ( $i = 0; $i < $character_length; $i++ ) {
						$hex_value   = bin2hex( $character[ $i ] );
						$obfuscated .= "%{$hex_value}";
					}
					break;
			}
		}

		if ( 0 !== $invalid_length ) {
			$obfuscated .= substr( $email_address, $at, $invalid_length );
		}

		$at += $invalid_length;
	}

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