On my website I have a couple of forms where someone (without registration) can send message to specified, registered user. The form is simple, and I want to keep that way. What is the best way to protect a contact form againts spam and bots if I don't want to use any captcha?
Your message:...
Your e-mail:...
[Send]
You can protect your form with the form keys technique:
Without a captcha or something comparable, it is impossible to really protect a form from abuse.
However, using this technique a malicious spammer would have to
This technique also protects your form from multiple accidential submissions.
Here is a code example:
<?php
session_start();
if (isset($_POST['form_submit'])) {
// do stuff
if (isset($_POST['formkey']) && isset($_SESSION['formkeys'][$_POST['formkey']])) {
echo "valid, doing stuff now ... "; flush();
// delete formkey from session
unset($_SESSION['formkeys'][$_POST['formkey']]);
// release session early - after committing the session data is read-only
session_write_close();
// do whatever you like with the form data here
send_contact_mail($_POST);
}
else {
echo "request invalid or timed out.";
}
}
else {
// show form with formkey
$formkey = md5("foo".microtime().rand(1,999999));
// put current formkey into list of valid form keys for the user session
if (!is_array($_SESSION['formkeys']) {
$_SESSION['formkeys'] = array();
]
$_SESSION['formkeys'][$formkey] = now();
?>
<html>
<head><title>form key</title></head>
<body>
<form method="POST">
<input type="hidden" name="PHPSESSID" value="<?=session_id()?>">
<input type="text" name="formkey"
value="<?= $formkey ?>">
<input type="submit" name="form_submit" value="Contact us!">
</form>
</body>
</html>
<?php } ?>
So the options:
Details on these and my opinion on them.
In my opinion, the best is solution 3, then solution 2, then solution 1, then solution 4 and 5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With