Skip to content

Instantly share code, notes, and snippets.

@walterdavis
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walterdavis/d8c6a4949a845d45747d to your computer and use it in GitHub Desktop.
Save walterdavis/d8c6a4949a845d45747d to your computer and use it in GitHub Desktop.
Example of a PHP "honeypot" form
<?php
// set up variables
$name = $comment = $error_string = '';
$errors = array();
// define success behavior
function thanks(){
header('Location: thanks.html');
exit;
}
// was the form submitted?
if(isset($_POST['url'])){
if(!empty($_POST['url'])){
// this is likely a spam bot
// redirect to thanks page without doing anything
thanks();
}else{
// probably not a bot
// populate variables
$name = trim(strip_tags($_POST['name']));
$message = trim(strip_tags($_POST['message']));
// basic error checking, can be as complex as you need
if(empty($name)){
$errors['name'] = 'Name cannot be empty';
}
if(empty($message)){
$errors['message'] = 'Didn’t you have anything to say?';
}
// if there are errors...
if(count($errors) > 0){
// human-readable error message
$error_string = '<ul class="errors"><li>' . implode('</li><li>', $errors) . '</li></ul>';
// fall through to show the form and errors
}else{
// do whatever you do to store the nice submission here
//
// then redirect to your thanks page
thanks();
}
}
}
// initial visit (or submission with errors), show the form
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Honeypot form example</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css" media="screen">
label { display: block }
/* the honeypot field is hidden */
#url { display: none }
</style>
</head>
<body>
<?= $error_string ?>
<!-- post the form to itself -->
<form action="" method="post" accept-charset="utf-8">
<label for="name">Name</label><input type="text" name="name" value="<?= $name ?>" id="name"/>
<label for="comment">Comment</label><textarea name="comment" rows="8" cols="40"><?= $comment ?></textarea>
<!-- this is the "honeypot" trap field -->
<input type="text" name="url" value="" tabindex="40" id="url"/>
<p><input type="submit" value="Say it!"/></p>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment