A few days ago, after receiving yet another spam submission from the contact form on my portfolio website, I had an epiphany about how to implement a honeypot to block bots instead of a captcha (which nobody likes anyway). I posted about this on Twitter and user @markdeafmcquire asked how I did it.
I just figured out how to add a honeypot radio button to my contact form (PHP/HTML/CSS)
Rachele DiTullio (@racheleditullio) April 14, 2020
Sweet, how did you do it? (Any link to a guide or something would help me.)
markdeafmcguire (@markdeafmcguire) April 18, 2020
Captcha versus honeypot
Captchas are those annoying puzzles you have to solve in order to prove you’re human. They are often inaccessible to people with disabilities and they can be difficult to figure out and pass.
Honeypots are passive, often implemented as hidden form fields that bots will fill out and humans won’t. If that hidden form field has a value, then you know the submission is from a bot and can be rejected.
My honeypot solution
My website uses PHP code with HTML to display the contact form as well as doing a server-side check on the form data when submitted.
The first thing I had to add was a hidden honeypot form field to trip up bots. I used a radio button.
<label for="honeypot" aria-hidden="true" class="visually-hidden">Honeypot <input type="radio" name="honeypot" id="honeypot" style="display:none" value="1"></label>
- Include the
aria-hidden="true"
attribute on the<label>
element to hide the honeypot from assistive technologies - Use a CSS class to hide the
<label>
element from sighted users - Add
style="display:none"
to the<input>
element, which prevents keyboard users from tabbing to the radio button
The second thing I had to add was a check in the PHP to determine if the radio button was selected when the form was submitted. I set the radio button to value="1"
and the form check fails if the value of honeypot==1
.
//check for honeypot
if ($_POST['honeypot'] == 1) {
$problem = TRUE;
}
Since it’s only been a few days, I don’t have enough data to determine if my solution is working well. I will update this post in the future.
Update December 2020
This solution has been working well for months now and I have not received any spam. Thanks to @AgenceCreatif on Twitter for trying out the code and offering feedback.
Accessible PHP honeypot form
Below is the PHP and HTML for adding an accessible contact form to your website, including the honeypot, and a way for people contacting you to send a copy of the email to themselves. Just update it with your email address.
See the Pen PHP Form Honeypot by Rachele (@racheleditullio) on CodePen.
Reach out to me on Twitter if you have anything to add.