your image

PHP Form Variables

quackit
Related Topic
:- PHP

Here, we discuss how to use PHP to work with variables submitted with a form.

Many website applications rely on HTML forms so that users can perform their tasks. For example, most Content Management Systems allow users to provide content for a website by entering the content into a textarea form field, then clicking a "Save" button. When the user clicks the Save button, the form is submitted to the action page. The action page is normally specified with the action attribute of the form tag.

If you're not familar with HTML forms, see the HTML forms section of the HTML tutorial, then return to this page.

Once a form has been submitted, the form fields are made available to the action page as a special type of variable. You, as the programmer, can read these form variables by using the appropriate syntax for form variables. Form variables are stored as an array. We will be covering arrays later, but for now all you need to know is how to read each form variable.

Forms can be submitted using one of two methods: get or post. By default, a form will be submitted using the "get" method. This results in each form variable being passed via the URL. If you decide to use the "post" method, you specify this using the method attribute ( method="post" ) of the form tag.

The Get Method

If you use the get method, your action page can access each form field using $_GET["variableName"] (where "variableName" is the name of the form field).

Example

Form page

 Run

Stack editor Unstack editor

 

<form action="/php/tutorial/php_action_page1.php" method="get">
<input type="text" name="firstName" /><br />
<input type="text" name="lastName" /><br />
<input type="submit" />
</form>

 

Action page (php_action_page1.php):

Here, the action page outputs the contents of the form variables that were passed from the form.

 

 
<html>
<head>
<title>PHP Form Variables Example</title>
</head>
<body>
First Name: <?php echo $_GET["firstName"]; ?><br />
Last Name: <?php echo $_GET["lastName"]; ?>
<p><a href="javascript:history.go(-1)">Back</a></p>
</body>
</html>

The Post Method

If your form uses the post method, you use $_POST["variableName"].

Example

Form page

 Run

Stack editor Unstack editor

 

 
<form action="/php/tutorial/php_action_page2.php" method="post">
<input type="text" name="firstName" /><br />
<input type="text" name="lastName" /><br />
<input type="submit" />
</form>

 

Action page (php_action_page2.php):

Here, the action page outputs the contents of the form variables that were passed from the form.

Comments