This article explains about form processing in PHP. Users enter various data in a HTML form through different HTML controls. We will see how to process that data in a PHP script.
One of the applications of PHP is processing the data provided by the users in (X)HTML forms. PHP provides two implicit arrays $_GET and $_POST which are global variables and are accessible anywhere in a PHP script.
The array $_GET is used when the attribute method of the form tag is set to GET and the array $_POST is used when the attribute method of the form tag is set to POST. Both arrays contain the form data stored as key-value pairs, where key contains the value of name attribute of the form element and value contains the value of the value attribute of the form element.
Below example demonstrates validation of user input in a simple (X)HTML form using PHP:
//HTML Code
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form action="validate.php">
Username: <input type="text" name="txtuser" /><br />
Password: <input type="password" name="txtpass" /><br />
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</form>
</body>
</html>
By default when the method attribute is not set, it will be implicitly set to GET. So, in PHP we have to use the array $_GET to retrieve the form data as shown below:
//PHP Code - validate.php
<?php
$user = $_GET["txtuser"]; //txtuser is the name of textfield in the HTML form
$pass = $_GET["txtpass"]; //txtpass is the name of password field in the HTML form
if($user == "")
print("Username cannot be empty!");
elseif($pass == "")
print("Password cannot be empty!");
else
print("Login success! <a href='home.html'>Click Here</a> to proceed");
?>
A tutorial explaining how to process the data entered by the users in HTML forms:
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply