Last active
March 13, 2024 08:21
-
-
Save antic183/848ac065ecc087fcd4f094b90c93eb37 to your computer and use it in GitHub Desktop.
a very simple and effectively way to hide email from spam bots
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$email = '[email protected]'; // when email-domain-part contains umlauts, use the idn format: idn_to_ascii('your-email@example-äöü.com'); | |
$emailLength = mb_strlen($email); | |
$randomFactor = ''; | |
$encodedMail = ''; | |
for ($ix = 0; $ix < $emailLength; $ix++) { | |
$randomFactor .= rand(1, 9); | |
} | |
foreach (str_split($email) as $currentIndex => $c) { | |
if ($c !== '@') { | |
bendIntoShapeCurrentCharacter($randomFactor, $c, $currentIndex); | |
$encodedMail .= encodeCharacter($c, str_split($randomFactor)[$currentIndex]); | |
} else { | |
$encodedMail .= '@'; | |
} | |
} | |
function encodeCharacter($character, $factor) { | |
$charCode = mb_ord($character); | |
$charEncoded = $charCode + $factor; | |
return mb_chr($charEncoded); | |
} | |
function bendIntoShapeCurrentCharacter(&$randomFactor, $c, $currentIndex) { | |
if (preg_match('/[^\w\.]+/i', encodeCharacter($c, str_split($randomFactor)[$currentIndex]))) { | |
$randomFactor[$currentIndex] = rand(1, 9); | |
bendIntoShapeCurrentCharacter($randomFactor, $c, $currentIndex); | |
} | |
} | |
?> | |
<a id="email" href="mailto:<?= $encodedMail; ?>">encodeded E-Mail</a> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> | |
<script> | |
(function($) { | |
'use strict'; | |
let factor = "<?= $randomFactor; ?>"; | |
function decodeCharacter(character, factor) { | |
return String.fromCharCode(character.charCodeAt(0) - factor); | |
}; | |
// Hide Email Address from Spambots, decode mechanism | |
function replaceMailTo() { | |
let element = this; | |
let tmp = JSON.parse(JSON.stringify(element)); | |
let currentMail = $(element).attr('href').split(':')[1]; | |
let decodedMail = ''; | |
let index = 0; | |
currentMail.split('').forEach(function(c) { | |
if (c !== '@') { | |
decodedMail += decodeCharacter(c, factor.split('')[index]); | |
} else { | |
decodedMail += '@'; | |
} | |
index++; | |
}); | |
// optional subject | |
decodedMail += '?subject=your-subject...'; | |
element.setAttribute("href", 'mailto:' + decodedMail); | |
$(element).removeAttr("id"); | |
}; | |
$(document).on('click', '#email', replaceMailTo); | |
})(jQuery); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment