Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with PHP in HTML forms

In this article we will learn how to work with php in html form. You will see how to submit a form with php.

PHP is known to be very effortless in handling the data submitted by the user through html forms. In this article we will talk about the different ways to read html form values from within a PHP script. This article will list down the methods applicable for different PHP versions.

When a form is submitted to a PHP script, the values from that form are made available to the script. There are many ways to access these values. Let’s start by looking at a sample html form.

Accessing form values:

Listing 1: Sample html form

<html>

<head><title>HTML being submitted to php script</title></head>

<body>
	
<form action="example.php" >
		<table width="100%">

    		<tr><td>Name:  <input type="text" name="username" /></td></tr>
    		<tr><td>Email: <input type="text" name="email" /></td></tr>
    	<tr><td><input type="submit" name="submit" value="Submit me!" /></td></tr>
</form>
</body>

</html>

Note: If the method is not specified in the form, default GET method is used.

In older versions of php, the values are accessible as globals. The sample php script to access the above form variables is listed below.

Listing 2: Old way of accessing form values

	<?php
		echo "Name = ".$username;
		echo "<br />";
		echo "Email = ".$email;
		echo "<br />";
	?>

The above code works only if the PHP directive register_globals is set to on. Prior to version 4.2, this was the default. Starting from version 4.2 the default setting of register_globals is off. register_globals can be turned on by adding the following directive in the .htaccess file.

php_flag register_globals on

Because this method of accessing html form values depends on a setting (to which developers might not have access to, especially in a shared server setup), it is better not to use this way.

Since version 4.2, html form variables can be accessed in three different ways as shown below.

Listing 3: Sample php script to access variables in form in listing 1

<?php 
echo $_GET['username'] <http://www.php.net/manual/en/reserved.variables.get.php>;    // available in PHP 4.1.0
echo "<br />";
echo $_GET['email'] <http://www.php.net/manual/en/reserved.variables.get.php>;
echo "<br />";
echo $_REQUEST['username'];
echo "<br />";
echo $_REQUEST['email'];
echo "<br />";
//Following function is deprecated in PHP 5.3 and removed in PHP 5.4
import_request_variables('p', 'p_');    

echo $p_username;
echo "<br />";
echo $p_email;
?>

The import_request_variables function provides a way to selectively register sets of globals. This function is available for versions 4.1 and also in its higher version.

If, in the html, the method attribute in form tag is specified as POST, then the way to access the values is as shown in Listing 4 below.

Listing 4: Methods to access POST method form values

echo $_POST['username'] <http://www.php.net/manual/en/reserved.variables.get.php>;    // available in PHP 4.1.0
echo "<br />";
echo $_POST['email'] <http://www.php.net/manual/en/reserved.variables.get.php>;
echo "<br />";

Note: Dots and spaces in variable names are converted to underscores. For example becomes $_REQUEST["a_b"].

In older (previous to version 4.1) versions of PHP, there is another way of accessing form values without using global. $HTTP_GET_VARS and $HTTP_POST_VARS arrays can be used for this purpose. These collections are deprecated since version 4.1, but they are still applicable and available. These are also used widely.

Both of these arrays are of a type hash tables. A hash table can be defined as an array which is indexed by string values compared to integers. But if we consider forms then the values are usually accessible by their name, as shown in listing.

Listing 5: Accessing form values through hash tables - GET method

	echo $HTTP_GET_VARS['username'];	
	echo "<br />";
	echo $HTTP_GET_VARS['email'];
	   echo "<br />";

For POST requests, the code would look as shown in listing 6.

Listing 6: Accessing form values through hash tables - POST method

	echo $HTTP_POST_VARS['username'];
	
	echo "<br />";

	echo $HTTP_POST_VARS['email'];
	   echo "<br />";

Accessing complex form values:

Until now, we have seen how to access simple input field values in php. Now, we’ll have a look at how to access complex form values like combo box selections and checkbox values.

The form that we will read is given below in listing 7.

Listing 7: Html form with complex types

<html>

<head><title>HTML being submitted to php script</title></head>

<body>
	
<form action="exampleComplex.php" >
		<table width="100%">

    		<tr>
	<td>
           <select name="countries[]" multiple="multiple">
                   <option value="India">India</option>
                   <option value="USA">USA</option>
                   <option value="France">France</option>
           </select>
       </td>
</tr>

<tr><td><input type="checkbox" name="account" value="Account">Have a bank account</td></tr>
		</table>
	</body>
</html>

The php script to access the combo-box and checkbox values is given below in listing 8.

Listing 8: Accessing form values as array

$country_values = $HTTP_GET_VARS['countries']; 
echo "0) ".$country_values[0];
echo "<br />";
echo "1) ".$country_values[1];
echo "<br />";
echo "2) ".$country_values[2];

Depending on how many countries had been selected, the values will appear. Rest of the values will be left blank. For example, if the form is submitted with two values - India and France, then the above php script will output the following.

  • India
  • France

To determine how many values were submitted, the sizeof() function can be used. The submitted values can then be accessed as shown in listing 9.

Listing 9: Retrieving form values from array

for ($i = 0; $i < sizeof($country_values); $i++) {
    echo $country_values[$i];
    echo "<br />";
}

Checkboxes in html forms can be accessed in a similar way. Given below is part of the html form

Listing 10: Html form with check box

<input type="checkbox" name="account" value="Account">Have a bank account
 

In php script, the above checkbox is accessed as:

Listing 11: Accessing checkbox value in php

$account _value = $HTTP_GET_VARS['account']; 
echo $account_value;

if (isset($account_value)) {
  //The checkbox was clicked
} else {
  //The checkbox wasn't clicked
}
 

If the checkbox is not checked, the value is not submitted. In such cases, the value of $account_value would be null. So, effectively, the very absence of a check box value tells us that it was not checked by the user.

Accessing all form values:

If we want to access all form values generically, php arrays or hash tables can be used.

Since $HTTP_GET_VARS returns a hash-table, properties of arrays can be used to manipulate them in the following way.

Listing 12: Accessing all form values


$form_fields = array_keys($HTTP_GET_VARS);
for ($i = 0; $i < sizeof($form_fields); $i++) {

    $myfield = $form_fields[$i];
    $myValue = $HTTP_GET_VARS[$myField];
    echo $myField ." = ". $myValue;
    echo "<br />";  

}

Here, first the array of form field names is retrieved. Then, we loop over it to get the actual field names. This field name is then used to retrieve the value.

Applying this script for our sample html form would yield the following page;

username = John
email = john@hotmail.com <mailto:john@hotmail.com>
countries = Array 

Note that the selected values of the combo box ‘countries’ have not been printed. To handle this, we’ll have to detect any arrays with the is_array() function. Here’s how the script would look like.

Listing 13: Handling arrays in form values

$form_fields = array_keys($HTTP_GET_VARS);
for ($i = 0; $i < sizeof($form_fields); $i++) 
{

    $myfield = $form_fields[$i];
    $myValue = $HTTP_GET_VARS[$myField];
    if (is_array($myValue)){
        for ($j = 0; $j < sizeof($myValue); $j++) {
            echo $myField ." = ". $myValue[$j];
            echo "<br />";
        }
    } else {
        echo $myField ." = ". $myValue;
    }

    echo "<br />";  

}

Conclusion

In this article, we looked at many different ways to access form values from within a php script. We started with globals, looked at using import_request_variables() to selectively register sets of globals. Then we visited methods $_GET / $_POST and $_REQUEST. Then we moved on to retrieving form values as arrays using the $HTTP_GET_VARS method. In the process, we learnt methods to manipulate php arrays or hash-tables.

When using these methods, we need to keep in mind the version of php that we are running. This is because the methods described in this article are available in specific versions of php. The versions have been mentioned while describing the methods.

See also



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login