8 December 2009

Secure PHP Form Without Captacha

Update, also see: Secure PHP Form With Captcha.

Here we have a Secure PHP Form without captcha. This script does not use any captcha protection but I will be adding another version very shortly which does use 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 43 and change the $to variable to your own email address.




<!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>

<?php
// Check if form has been submitted
if (isset($_POST['submit'])) {
// Form has been submitted
// 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";
mail($to,$subject,$message,$headers);
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 />
<input type="submit" name="submit" value="Submit Form" />
</form>

<?php
}
?>

</body>
</html>

0 comments:

Post a Comment