Access Form Data from PHP

HTML forms are used to allow users to interact with the application. Form holds fields like, input box, dropdown, textarea, check box, radio buttons and etc. User can enter and submit their own data through these fields. These data will be processed by the PHP script. Now we are going to discuss about how to access user data from PHP program.

php_and_forms

In HTML, <form> tags are used to create forms which includes three frequently used attributes as name,action and method.

  • name – This represents name of the form, which are used to validate form fields using JavaScript.
  • action – This holds an URL as its value to which the form will be submitted on clicking submit button.
  • method – These might be either GET method or POST method. By default, it is taken as GET, if you did not specify anything. If the method is GET, then the form fields are sent through the Querystring which are visible in the address bar of you browser.

Let us see an example to access HTML form from a separate PHP page:

<HTML>
<HEAD>
<TITLE>User Form</TITLE>
</HEAD>
<BODY>
<FORM NAME="frmUser" ACTION="user.php" METHOD="post">
<P>
User Name: <INPUT TYPE="text" NAME="txtUser"><br>
</INPUT TYPE="submit" name="submit" value="Submit">
</P>
</FORM>
</BODY>
</HTML>

Save this file as user.html. And then, save the following PHP code as user.php.

<?php
$user_name = $_POST["txtUser"];
echo $user_name;
?>

When we open user.html in browser, then we would be required to submit form after entering our name. On submit, user.php will be called as specified in action field. In that PHP page, form fields are accessed using superglobal variable, that is, $_POST, since form method is represented as post. If form method has value as get or it doesn’t has any value, then the form field should be accessed by $_GET.

If the action is empty, then form will be submitted to the same page where the it is. So we need to combine the PHP script with HTML as shown in the following code.

<?php
if($_POST["submit"]) {
$user_name = $_POST["txtUser"];
echo $user_name;
}
?>

<HTML>
<HEAD>
<TITLE>User Form</TITLE>
</HEAD>
<BODY>
<FORM NAME="frmUser" ACTION="" METHOD="POST">
<P>
User Name: <INPUT TYPE="text" NAME="txtUser"><br>
</INPUT TYPE="submit" name="submit" value="Submit">
</P>
</FORM>
</BODY>
</HTML>

This program will create the same output as the above one. Since, the action is empty, the same script will be called on submit. PHP code at the beginning will check, whether the form is submitted. If not, the program will not print anything to the browser.

This HTML code tutorial was published on April 21, 2013.

↑ Back to Top