Test Form

PHP Form Validation Example

Name:

E-mail:

Website:

Comment:

Gender: Female Male Other

Your Input:





<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

// superglobals that needs to be sanitized
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}

// function to sanitize the superglobals
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

// sanitize the post action
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> ...

<?php
// display the sanitized information
echo "<h3>Your Input:</h3>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>