Get value from form in php

Example of using PHP to get a value from a form:

Put this in foobar.php:



  

Read the above code so you understand what it is doing:

"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php and the below code is run.

Put this code in foobar_submit.php in the same directory as foobar.php:


"; print_r($_POST); ?>

Read the above code so you know what its doing:

The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".

Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.

The value of the input tag with name=my_html_input_tag was put into the $_POST and you retrieved it inside another PHP file.

HTML form data can be retrieved and processed in many different ways, for example

  • by using a scripting language,
  • a server-side language such as PHP,
  • or any of the many programming languages of choice.

In this tutorial, we’re going to walk you through on how to access or retrieve form data with PHP, and show you the different methods that can be used.

Setting up the HTML form

To set up a form for server processing and data retrieval, two important form attributes that controls how the form data is processed whenever it is submitted must be specified. These two form attributes are:

  • Method Attributes
  • Action Attributes

{codecitation}

{/codecitation}

Action Attributes: specifies the PHP script file location for processing when it is submitted. If no script file location is specified, the browser submits the form by using the current PHP script file location ( the self-script in which the form is being called ).

Method Attributes: specifies what type of method the form will use to send the data. We have two methods, the GET and POST.

Note: By default, if no method is specified, the GET method is used.

Setting access keys for the form data by using the element’s name attribute

The element’s name attribute ( name=”unique-name-here” ) value is used by PHP as key to enable access to the data value of the specified form field element when you submit the form. Without the name attribute specified for each element contained in the form, PHP will be unable to create an array automatically with an access key by using the element’s name attribute value. This means you can’t access that element form data value after the form has been submitted to the server because its key is undefined.

{codecitation}name=”unique-name-here” />{/codecitation}

How form data is sent

When you submit the form to the server, it encodes it by using a scheme called URL encoding which has a built-in pattern that describes how the form data is parsed and encoded. This scheme parses and encodes the form data as a name/value pairs, and it uses the equal sign (=) to concatenate the name/value pairs together.

{codecitation}name=value{/codecitation}

However, if the form data to be sent consists of different pairs, the ampersand character (&) is used to separate them.

{codecitation} name1=firstValue&name2=secondValue&name3=thirdValue {/codecitation}

Also, if the form data to be sent contains the space character, the scheme replaces it with the plus character (+), and every other non-word characters present is encoded differently.

How send works

Client browsers can send information to a web server in two different ways:

  1. GET Method
  2. POST Method

The GET Method

This method instructs the browser to send the encoded information (the name/value pairs) through the URL parameter by appending it to the page request. The browser implement this method by concatenating the question mark character (?) to the end of the page request since it specifies where the query string (name/values pairs) starts from, and all the form data is visible to everyone as it is displayed in the browser address bar.

Example: How the form GET method data is submitted

URL parameters explained

  • http://localhost/example.com: Specifies the page request. It is the page the browser is requesting from the server.
  • ?: This character specifies where the query string for the requested page starts from. When it is omitted, the browser won’t understand how to handle and send the query string (name/values pairs) to the server.
  • name1, name2: Specifies the form field element’s name attribute value. Each is assigned to its corresponding form field data, and it is used as the access key by the server script (PHP), to retrieve its data value when you fill out the form and submit it.
  • firstValue, secondValue: These are the inputted values you entered before submitting the form. Each Value is assigned to its corresponding element’s name attribute value.
  • &: This character is used to concatenate the name/value pairs together as one long query string.
  • =: This character is used to assign the name of the form field element to its data value as a name/value pair.

How to retrieve form data sent via GET

When you submit a form through the GET method, PHP provides a superglobal variable, called $_GET. PHP uses this $_GET variable to create an associative array with keys to access all the sent information ( form data ). The keys is created using the element’s name attribute values.

The $_GET Method Script: get-method.php

{codecitation} // Check if the form is submitted if ( isset( $_GET[‘submit’] ) ) { // retrieve the form data by using the element’s name attributes value as key $firstname = $_GET[‘firstname’]; $lastname = $_GET[‘lastname’]; // display the results echo ‘

Form GET Method

’; echo ‘Your name is ‘ . $lastname . ‘ ‘ . $firstname; exit;
}
{/codecitation}

The GET method

{codecitation}

{/codecitation}

Here is an image showing the code output:

Get value from form in php

Now let’s take a look at the code …

The PHP isset() function is used to determine if a variable is set and is not null.

Firstly, the isset() function checks if the form has been submitted by using the element’s name attribute value “submit” (name=”submit”) as key and pass it to the $_GET[] superglobal variable. This is because the form data are stored in the $_GET[] superglobal array by PHP when it is submitted through the GET method.

Then the form field, first name and last name form data are retrieved by using the same method, passing their respective name attribute values into the $_GET[‘name as key’] array parameter, and each is assigned to a variable name that was used to display the results.

Using the POST

The form POST method sends information via HTTP header. All name/value pairs sent through this method is invisible to anyone else since all the information are embedded within the body of the HTTP request.

When you submit a form to a server through the POST method, PHP provides a superglobal variable called $_POST. The $_POST variable is used by PHP to create an associative array with an access key ($_POST[‘name as key’]). The key is created automatically by PHP when the form is submitted. PHP uses the form field element name attribute (name=”unique-name-here”) to create the key.

The $_POST Method Script: post-method.php

{codecitation}// Check if the form is submitted if ( isset( $_POST[‘submit’] ) ) { // retrieve the form data by using the element’s name attributes value as key $firstname = $_POST[‘firstname’]; $lastname = $_POST[‘lastname’]; // display the results
echo ‘

Form POST Method

’; echo ‘Your name is ‘ . $lastname . ‘ ‘ . $firstname; exit; } {/codecitation}

The POST method form

{codecitation}


{/codecitation}

Code explained

isset( $_POST[‘submit’] ) : This line checks if the form is submitted using the isset() function, but works only if the form input type submit has a name attribute (name=”submit”).

$_POST[‘firstname’]: The form data is stored in the $_POST[‘name as key’] variable array by PHP since it is submitted through the POST method, and the element name attribute value – firstname (name=”firstname”) is used to access its form field data. The same procedure is used for $_POST[‘lastname’]. The form data is then assigned to a variable that was used to display the results.

The $_REQUEST variable

The $_REQUEST variable is another PHP superglobal variable that you can use to dynamically retrieve form data sent from both Form GET and POST methods. The $_REQUEST variable contains the content of both $_GET, $_POST and $_COOKIES.

Note: the $_COOKIES superglobal variable is used for creating COOKIES data. We will discuss this in a different tutorial.

Example: request-script.php

The $_REQUEST variable code

{codecitation} // Check if the form is submitted
if ( isset( $_POST[‘submit’] ) ) {

// retrieve the form data by using the element’s name attributes value as key

echo ‘

form data retrieved by using the $_REQUEST variable

$firstname = $_REQUEST[‘firstname’];
$lastname = $_REQUEST[‘lastname’];

// display the results
echo ‘Your name is ‘ . $lastname .’ ‘ . $firstname;

// check if the post method is used to submit the form

if ( filter_has_var( INPUT_POST, ‘submit’ ) ) {

echo ‘

form data retrieved by using $_POST variable

$firstname = $_POST[‘firstname’];
$lastname = $_POST[‘lastname’];

// display the results
echo ‘Your name is ‘ . $lastname .’ ‘ . $firstname;
}

// check if the get method is used to submit the form

if ( filter_has_var( INPUT_GET, ‘submit’ ) ) {

echo ‘

form data retrieved by using $_GET variable

$firstname = $_GET[‘firstname’];
$lastname = $_GET[‘lastname’];
}

// display the results
echo ‘Your name is ‘ . $lastname .’ ‘ . $firstname;
exit;
}
{/codecitation}

The form code

{codecitation}


{/codecitation}

Code explained

The $_REQUEST variable script code works exactly the same way as the previous $_GET and $_POST code script above. The only task required is to replace the $_GET and $_POST with the $_REQUEST variable.

The filter_has_var() function

It checks if a variable of a specified input type exists. It has two parameters, filter_has_var( type, variable_name ), and both parameters are required. The first parameter type specifies the input type to check for, which can be any of the following constant values ( INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV). The second parameter input specifies the variable name (the name attribute of the form input element, name=”unique-name-here”) to check.

Anatomy of the GET method

  • The GET method produces a long query string that is displayed in the browser’s address bar when the form is submitted.
  • The GET method should not be used to send sensitive content/information like password because all of the content/information is displayed in the browser’s address bar.
  • When sending form data through the GET method, you can only send a maximum of 2048 characters.
  • The GET method cannot be used to send binary data like images, mp3 or pdf files to the server.
  • When you submit a form through the GET method, PHP creates a $_GET associative array in this format, $_GET[‘name as key’] to enable you to retrieve the form data.
  • The GET method is suitable to send non-sensitive content/information to the server.

Anatomy of the POST method

  • The POST method sends information via HTTP header, all the information are embedded within the body of the HTTP request.
  • The POST method can be used to send sensitive content/information since all data are sent through the HTTP header.
  • This method has no limit on the amount of information to send to the server.
  • The POST method provides support to send binary data like images, mp3 or pdf files, and also provides enhancement for file uploading to the server.
  • When you submit a form through the POST method, PHP creates a $_POST associative array in this format, $_POST[‘name as key’] to enable you to retrieve the form data.

Form validation

We are going to filter and sanitize the inputted data by using the PHP preg_replace() function. Although, the PHP filter extension can be used to perform the same task.

{codecitation} // {/codecitation}

The Preg_replace() function

This function performs a regular expression search and replace.

{codecitation}preg_replace( $pattern, $replacement, $subject, $limit, $count ){/codecitation}

Note: The $limit and $count parameters are optional. Both can be omitted.

Example: The preg_replace() function code

{codecitation} $firstname = preg_replace( “#[^\w]#”, “”, $_POST[‘firstname’] );

$lastname = preg_replace( “#[^\w]#”, “”, $_POST[‘lastname’] ); {/codecitation}

Code explained

The first parameter: “#[^\w]#” represents a Regular Expression pattern, the function uses this pattern and validates it against a Regular Expression word character (\w). \w is a Regex metacharacter that matches only word characters ( the alphabet A to Z uppercase or a to z lowercase, and the underscore character _ ). The [^\w] matches any non-word characters. The hash character (#) is the regular expression modifier.

The second parameter: “” is what the function will use to replace any non-word characters found in the inputted values. In this case, we’re replacing any nonword characters found with an empty string.

The third parameter: $_POST[‘firstname’] or $_POST[‘lastname’] represents the inputted values you entered into the form field. The function checks the characters that is contained in this third parameter, and then validates it against the expression (match any non-word character) in the first parameter, if any non-word character is found, the function replaces it with the value in the second parameter (an empty string).

How can I access form data in PHP?

$_POST['firstname']: The form data is stored in the $_POST['name as key'] variable array by PHP since it is submitted through the POST method, and the element name attribute value – firstname (name=”firstname”) is used to access its form field data.

What is used to retrieve values from HTML form in PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post".

How will you retrieve values submitted by this form?

Since the form data is sent through the post method, you can retrieve the value of a particular form field by passing its name to the $_POST superglobal array, and displays each field value using echo() statement.

How can get input field value in PHP variable?

In order to get an input value, you can use the htmlspecialchars() method and $_REQUEST variable. Note: The htmlspecialchars() method functions by converting special characters to HTML entities. The $_REQUEST variable is a built-in PHP variable that functions by getting data from the input field.