Validate Form Data With PHP

Validating form data with php is essential to avoid security issue with your website. The hacker can use your form to input the virus or the script to hack important data from your website.

Let check the Html form that validates your form details.

Example

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

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 test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>[/php]

PHP Form Validation Example

[php]<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>[/php]

[php]<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>[/php]

In the above example, we are using PHP_SELP method to get the data of the php. When form executed the user will see the details on the same page.

In the php function first step is to define the variable with empty values.

$name = $email = $gender = $comment = $website = "";

Next we will be using if statement to assign the request method at post value. In this code we have added each variable to its html form value and we have given test_input a function name to the value.

[php]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"]);
}[/php]

After that, we will be verifying the user’s input data with the php functions. To do that we will be running our function text_input($data) through the security check php functions as given below.

[php][/php]function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

The php function trim() is actually trims the data by removing unwanted space from the user’s input.

The function stripslashes() removes the lash from the input data.

The function htmlspecialchars() replace the special characters to the HTML format.

In the end, we get the result of the users on the page. You need to use echo statement to get the form details to present on the page.

Related Posts

Leave a Reply