Quick Contact

    Presenting the User with Input Options via Different HTML Form Elements

    In form , the most important element is the <input> element.The <input> element can be displayed in several ways, depending on the type attribute.

    An example of this tag is:

    <input name="firstname" type="text">
    The <select> Element

    The <select> element defines a drop-down list:

    An example of this tag is:

    <select name="cars">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>
    
    The <option> Element

    The <option> elements defines an option that can be selected.By default, the first item in the drop-down list is selected.To define a pre-selected option, add the selected attribute to the option:

    An example of this tag is:

    <option value="fiat" selected>Fiat</option>
    Visible Values

    The size attribute can be used to specify the number of visible values:

    An example of this tag is:

    <select name="cars" size="3">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>
    
    Allow Multiple Selections

    We can use the multiple attribute to allow the user to select more than one value:

    An example of this tag is:

    <select name="cars" size="4" multiple>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>
    
    The <textarea> Element

    The <textarea> element defines a multi-line input field (a text area):

    An example of this tag is:

    <textarea name="message" rows="10" cols="30">
    The cat was playing in the garden.
    </textarea>
    
    • The rows attribute specifies the visible number of lines in a text area.
    • The cols attribute specifies the visible width of a text area.
    The <button> Element

    The <button> element defines a clickable button:PHP 

    An example of this tag is:

    <button type="button" onclick="alert('Hello World!')">Click Me!</button>

    To show the values in the input fields after the user hits the submit button, we add a little script inside the value attribute of the following input fields: name, email, and website. In the comment textarea field, we put the script between the <textarea> and </textarea> tags. The little script outputs the value of the $name, $email, $website, and $comment variables.

    Then, we also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons):

    The code for PHP form is:

    Name: <input type="text" name="name" value="<?php echo $name;?>">
    Email: <input type="text" name="email" value="<?php echo $email;?>">
    Website: <input type="text" name="website" value="<?php echo $website;?>">
    Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
    Gender:
    <input type="radio" name="gender"
    <?php if (isset($gender) && $gender=="female") echo "checked";?>
    value="female">Female
    <input type="radio" name="gender"
    <?php if (isset($gender) && $gender=="male") echo "checked";?>
    value="male">Male
    
    <input type="radio" name="gender"
    <?php if (isset($gender) && $gender=="other") echo "checked";?>
    value="other">Other
    

    Two methods are used to submit data from form. They are :

    • $_GET
    • $_POST

    Both GET, and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, …)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

    Both GET, and POST are treated as $_GET and $_POST. These are superglobal, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.

    $_GET is an array of variables passed to the current script via the URL parameters.

    $_POST is an array of variables passed to the current script via the HTTP POST method.

    $_GET

    Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

    GET may be used for sending non-sensitive data.

    $_POST

    Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

    Moreover, POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

    However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

    Retrieving Form Data with $_POST,$_GET and $_REQUEST Arrays

    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.
    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
    <form action="" method=""> ... </form>

    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.

    <input type="text" name="unique-name-here" />
    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.

    name=value

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

    name1=firstValue&name2=secondValue&name3=thirdValue

    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:

    • GET Method
    • 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

    // Checkif 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 '<h3>Form GET Method</h3>'; echo 'Your name is ' . $lastname . ' ' . $firstname; exit;}
    
    The GET method
    <form action="get-method.php" method="get">
    	<input type="text" name="firstname" placeholder="First Name" />
    	<input type="text" name="lastname" placeholder="Last Name" />
    	<input type="submit" name="submit" />
    </form>
    

    Here is an image showing the code output:

    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

    // 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 '<h3>Form POST Method</h3>'; echo 'Your name is ' . $lastname . ' ' . $firstname; exit; } 

    The POST method form

    	<form action="post-method.php" method="post">
    	<input type="text" name="firstname" placeholder="First Name" />
    	<input type="text" name="lastname" placeholder="Last Name" />
    	<input type="submit" name="submit" />
    </form>
    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

    // 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 '<h2>form data retrieved by using the $_REQUEST variable<h2/>'
    $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 '<h2>form data retrieved by using $_POST variable<h2/>'
    $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 '<h2>form data retrieved by using $_GET variable<h2/>'
    $firstname = $_GET['firstname']; 
    $lastname = $_GET['lastname']; 
    }
    

    // display the results

    echo 'Your name is ' . $lastname .' ' . $firstname; 
    exit;}
    The form code
    <form action="demo/request-variable.php" method="post">
    	<input type="text" name="firstname" placeholder="First Name" />
    	<input type="text" name="lastname" placeholder="Last Name" />
    	<input type="submit" name="submit" />
    </form>
    
    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.

    //

    The Preg_replace() function

    This function performs a regular expression search and replace.

    preg_replace( $pattern, $replacement, $subject, $limit, $count )

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

    Example: The preg_replace() function code

    $firstname = preg_replace( "#[^\w]#", "", $_POST['firstname'] );
    $lastname = preg_replace( "#[^\w]#", "", $_POST['lastname'] );
    
    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).

    Preserving Data in Form Inputs Parallel Testing in Testing

    We use header() to redirect a user to the same page, all the form variables for that page are destroyed.

    As such, rather than using a querystring variable to echo out an error message, it makes more sense to build an error message string, and echo that on the same page, while retaining the form values.

    An example is shown below:

    if(isset($_POST['submit'])) {
       $ok = true;
       $message = "<p>There are problems with this form. Please correct the following errors:</p><ul>";s
    
       if(trim($_POST['name']) == "") {
          $message .= "<li>You did not enter your name.</li>";
          $ok = false;
       }
    	if(trim($_POST['email']) == "") {
          $message .= "<li>You did not enter your e-mail address.</li>";
          $ok = false;
       }
       if(trim($_POST['city']) == "") {
          $message .= "<li>You did not enter your city.</li>";
          $ok = false;
       }
       if(!$ok) {
          $message .= "</ul>";
       }
       else {
          $message = "";
          //your processing code goes here
       }
     
        echo $message;
    }
    
    Retaining Form Values on PHP Postback

    Echoing form variables back in the event a form did not properly process is easy in the technical sense, but time-consuming in the practical sense, because it means editing every form field to use the posted / gotten variables.

    Basically, you use the $_POST superglobal to echo out the values sent to the server (or $_GET, based on your form’s method attribute; you could also use $_REQUEST if you are mixing $_POST and $_GET variables in your form). The benefit of this method is that if the form hasn’t been sent to the server by the client, the relevant $_POST fields haven’t been populated, so nothing will show on initial page load.

    For example, if you have a standard text input, you add the value attribute, and make it the $_POST value for that field:

    <input type="text" name="foo" value="<?php echo $_POST['email']; ?>" />

    For a textarea:

    <textarea name="foo" cols="50" rows="5"><?php echo $_POST['email']; ?></textarea>

    For a radio button, we set the checked property to checked if the value of the radio button matches the value stored in the $_POST variable for that named field.

    <input type="radio" name="foo" value="bar" <?php if($_POST['foo'] == "bar") { echo "checked=\"checked\""; } ?> />

    A checkbox is a bit more involved, since checkboxes are treated as an array by PHP. Basically, we need to iterate all the values stored in the $_POST variable for that element, and set the checked property to checked if the box was originally checked. Note that because we are calling foreach, we need to ensure that the $_POST field we intend to iterate is set (thanks to bustin98 for pointing this out).

    <input type="checkbox" name="foo[]" value="bar" <?php if(isset($_POST['foo'])) { foreach($_POST['foo'] as $tmp) { if($tmp == "bar") { echo "checked=\"checked\""; break; }}} ?>

    A select list basically follows either the method used for radio buttons or checkboxes, depending on whether it is a single-select or multiple select, respectively. Except that with a select list, we actually add code to each option under the select, to see if it was selected.

    Clearing Form Values

    So, how dowe clear form values in PHP if the form was properly processed or you want the user to start over? Just unset the $_POST or $_GET variable, again depending on your form’s method.

    //clear all $_POST variables

    unset($_POST);
    Summary

    The points below summarize the topics discussed:

    • $_GET, $_POST and $_REQUEST is three superglobal http request methods used in PHP.
    • These methods are used to send and retrieve data from server.
    • $_GET requests the data from a specified resource and only limited amount of data can be sent.
    • $_POST submits the processed data to a specified resource where, large amount of data can be sent because data is sent in body.
    • $_REQUEST variable is another PHP superglobal variable that you can use to dynamically retrieve form data sent from both Form GET and POST methods.s
    • $_POST method can be used to retain the data that was sent. It can be used to save the data that was sent through form.

    Enrolled Yourself In Live Training – PHP Training

    Copyright 1999- Ducat Creative, All rights reserved.