Last active
March 28, 2025 10:39
-
-
Save Yalme/18542573e7f57e519856a204d20cecee to your computer and use it in GitHub Desktop.
Защита формы от спама (проверка js и скрытое поле)
This file contains hidden or 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
<? | |
define('YAL_FORM_JS_CHECK_FIELD_NAME', 'data_202503220134'); // поле создается для тех, у кого есть js | |
define('YAL_FORM_HONEYPOT_FIELD_NAME', 'data_202503220144'); // обычное невидимое поле-приманка для ботов | |
?> | |
<!-- добавляем в каждую форму --> | |
<textarea name="<?= YAL_FORM_HONEYPOT_FIELD_NAME ?>"></textarea> | |
<!-- добавляем один раз на страницу --> | |
<script> | |
// добавление поля к каждой форме на сайте | |
document.addEventListener('DOMContentLoaded', () => { | |
document.querySelectorAll('form').forEach(form => { | |
const hiddenInput = document.createElement('input'); | |
hiddenInput.setAttribute('type', 'hidden'); | |
hiddenInput.setAttribute('name', '<?= YAL_FORM_JS_CHECK_FIELD_NAME ?>'); | |
hiddenInput.setAttribute('value', '1'); | |
form.appendChild(hiddenInput); | |
}); | |
}); | |
</script> | |
<style> | |
[name="<?= YAL_FORM_HONEYPOT_FIELD_NAME ?>"] { | |
height: 0px !important; | |
opacity: 0 !important; | |
overflow: hidden !important; | |
} | |
</style> | |
<? | |
if (empty($_POST[YAL_FORM_JS_CHECK_FIELD_NAME])) exit('Error: javascript must be enabled.'); | |
if (!empty($_POST[YAL_FORM_HONEYPOT_FIELD_NAME])) exit('Ошибка: заполнено невидимое поле.'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment