This article will share the idea and concept of form validation uisng PHP.
We can also do form validation using PHP. We need to include the PHP coding with the HTML codes. For the PHP code the server must translate the PHP code into the HTML equivalent so that it can work in the browser.
Let's see how to do it with an example.
<html>
<head>
<title>Form validation through PHP</title>
</head>
<body>
<?php
//define variables and set them to empty values
$name=$email=$address=$contact="";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$name=test_input($_POST["name"]);
$email=test_input($_POST["email"]);
$address=test_input($_POST["address"]);
$contact=test_input($_POST["contact"]);
}
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
<h2>Form Validation</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name:<input type="text" name="name"><br>
Email:<input type="text" name="email"><br>
Address:<input type="text" name="address"><br>
Contact:<input type="text" name="contact"><br>
<input type="submit" name="submit" value="submit">
<input type="reset" name="reset" value="reset">
</form><?php
echo "<h2>Your Information</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $address;
echo "<br>";
echo $contact;
</body>
</html>
Output
Here, $_SERVER[“PHP_SELF”] is a super global variable that returns the filename of the currently executing script. It sends the submitted data to the page itself instead of jumping to the next page. This way the user gets his/her errors on that page only.
The htmlspecialchars() function converts special characters to html entities. This menas that it converts like < and > to < and >
And the other things are normal PHP and HTML code and you all might be familiar with all the tags and keywords.
Output after input