8 December 2009

Secure PHP Form With Captcha

Here we have a Secure PHP Form with captcha powered by reCAPTCHA.

I wrote this script based on three inputs (Name, Email, and Message) but you can edit it you fit your requirements. All three variables in this script go through a FILTER_SANITIZE_STRING which is used to filter out bad characters from the input. It also uses FILTER_SANITIZE_EMAIL to validate the email address.

You will need to edit line 58 and change the $to variable to your own email address.
For reCAPTCHA to work you will need to upload the recaptchalib.php file to the same directory as this script. You can download recapctahlib.php from http://recaptcha.googlecode.com/files/recaptcha-php-1.10.zip.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>Secure PHP Form</title></head>

<h1>Secure PHP Form</h1>

// Check if form has been submitted
if (isset($_POST['submit'])) {
// Form has been submitted

// ReCaptcha Image And Settings
$privatekey = "6LcgKgkAAAAAAA0i5ZtgaAyOVkwQn9FsX8qOaSef";
$resp = recaptcha_check_answer ($privatekey,

if (!$resp->is_valid) {
// Captcha was entered incorrectly
die ("Opps, the captcha image was incorrect. Go back and try again.");
} else {

// Captcha was entered correctly
// Check and validate name variable
if ($_POST['name'] != "") {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($name == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
} else {
$errors .= 'Please enter your name.<br/>';

// Check and validate email variable
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
} else {
$errors .= 'Please enter your email address.<br/>';

// Check and validate message variable
if ($_POST['message'] != "") {
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if ($message == "") {
$errors .= 'Please enter a valid message.<br/><br/>';
} else {
$errors .= 'Please enter your message.<br/>';

// Check for error in the form
if (!$errors) {
$to = "someone@example.com";
$subject = "Secure PHP Form";
$headers = "From: $email";
echo '<p>Form Submitted</p>';
} else {
echo '<div style="color: red">' . $errors . '<br/></div>';
} else {
// Form has now been submitted


<form name="secureform" action="secureform.php" method="post">
Name: *<br /><input type="text" name="name" size="35" /><br />
Email Address: *<br /><input type="text" name="email" size="35" /><br />
Message: *<br /><input type="textarea" name="message" /><br />

$publickey = "6LcgKgkAAAAAAEtp0C1bbBWYRNZvZgoMEXRz_eyO"; // you got this from the signup page
echo recaptcha_get_html($publickey);

<input type="submit" name="submit" value="Submit Form" />




Post a Comment