Forms

Forms revisited

  • HTML forms collect user inputs and are defined by the <form> element
    • The action attribute defines where (to which page) the form data is sent when the form is submitted
    • The method attribute defines the HTTP method (GET or POST) to be used when submitting the form data
      • Both GET and POST create an associative array ($_GET and $_POST, respectively)
        • The keys of this associative array are the names of the form elements
        • The values of this associative array are the values of the form elements, i.e., the inputs of the user
      • Information sent from a form with GET is visible to everyone (in the URL, e.g. http://localhost:5500/course/form_get_process.php?name=John&gender=M) and can be bookmarked. GET should not be used for sending sensitive data. GET is recommended when submitting "idempotent" forms that do not "significantly alter the state of the world", e.g. forms that involve only database queries.
      • Information sent from a form with POST is invisible to others and cannot be bookmarked. POST is recommended when database updates or other actions (such as sending emails) are involved. Yet, lots of developers always use POST for sending form data.
      • See "Methods GET and POST in HTML forms - what's the difference?" for a detailed explanation of the difference between GET and POST
  • An HTML form contains form elements, such as text fields, checkboxes, radio buttons, ...

Form with GET

  • Open course/form_get.php
<form method="get" action="form_get_process.php">
    <div>
        <label for="name"><b>Name:</b></label>
        <input type="text" name="name" id="name" placeholder="Your name here">
    </div>
    <div>
        <label><b>Gender:</b></label>
        <input type="radio" name="gender" id="male" value="M">
        <label for="male">Male</label>

        <input type="radio" name="gender" id="female" value="F">
        <label for="female">Female</label>

        <input type="radio" name="gender" id="nonbinary" value="X">
        <label for="nonbinary">Non-binary</label>
    </div>

    <button type="submit" class="btn-primary"><b>Submit</b></button>
</form>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Form with get

  • The action attribute describes that the form inputs are processed on another PHP page, i.e. course/form_get_process.php. Open this file.
<div class="margin-3">
    <p>Your inputs:</p>
    <ul>
        <li>Name: <span class="text-primary">
           <b><?php echo !empty($_GET['name']) ? $_GET['name'] : 'Not specified' ?></b></span>
        </li>
        <li>Gender: <span class="text-primary">
           <b><?php echo $_GET['gender'] ?? 'Not specified' ?></b></span>
        </li>
    </ul>
</div>
1
2
3
4
5
6
7
8
9
10
11
  • The associative array $_GET contains all the form inputs
  • Use the name attributes of the form fields (in this case 'name' and 'gender') as array keys to capture the specific values of the corresponding form elements
  • Special care has to be taken regarding empty form elements
    • If you don't select a gender, $_GET['gender'] equals null, resulting in an error if we echo this value.
      We can use the statement isset($_GET['gender']) ? $_GET['gender'] : 'Not specified') (or the shorter form $_GET['gender'] ?? 'Not specified') to test whether $_GET['gender'] exists. If not, we echo the string 'Not specified'.
    • If you don't fill in a name, $_GET['name'] gets the value '' (and not null!). Hence, we cannot use the isset() function to check for a missing name, but should use the empty() function instead: !empty($_GET['name']) ? $_GET['name'] : 'Not specified'
  • See PHP isset() vs empty() vs is_null() for a more in-depth discussion on the differences between isset() and empty()

Form with get: processed

REMARK

In this example, we only check the input values with PHP, which can be referred to as (some form of) server-side validation.
For a better user experience, it is advisable to validate the inputs on the client side as well before the form is submitted. This can be done e.g. by using HTML5's built-in form validation (special input types and attributes required, pattern, min, maxlength, ...). We will elaborate further on this topic when implementing the contact page in the Laravel part of the course (Laravel -> Contact).

Processing the inputs on the same page

  • Open course/form_get_self.php (which contains the same form as above)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


















 
 
 

<?php
if ($_GET){
    $name = !empty($_GET['name']) ? $_GET['name'] : 'Not specified';
    $gender = $_GET['gender'] ?? 'Not specified';
    echo <<<RESULTS
        <div class="margin-3">
            <p>Your inputs:</p>
            <ul> 
                <li>Name: <span class="text-primary"><b>$name</b></span></li>
                <li>Gender: <span class="text-primary"><b>$gender</b></span</li>
            </ul>
        </div>
        <p><a href="{$_SERVER['PHP_SELF']}">Back</a></p>
    RESULTS;
} else {
?>
<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <div>
        <label for="name"><b>Name:</b></label>
        <input type="text" name="name" id="name" placeholder="Your name here">
    </div>
    <div>
        <label><b>Gender:</b></label>
        <input type="radio" name="gender" id="male" value="M">
        <label for="male">Male</label>

        <input type="radio" name="gender" id="female" value="F">
        <label for="female">Female</label>

        <input type="radio" name="gender" id="nonbinary" value="X">
        <label for="nonbinary">Non-binary</label>
    </div>

    <button type="submit" class="btn-primary"><b>Submit</b></button>
</form>
<?php
}
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  • Now, the action attribute equals $_SERVER['PHP_SELF'], which means that the form inputs are processed on the same page
    • The variable $_SERVER['PHP_SELF'] is also used in the 'Back' link at the bottom of the page
  • When the form is submitted, the $_GET array contains at least one array element (i.e., $_GET['name'], see above). An array with elements evaluates to true, and, hence, we show the processed inputs.
    In the other case (the page is loaded without submitting), the $_GET array has no elements. An array with no elements evaluates to false and we show the form.

REMARK

We use the heredoc syntax to show the processed form input values. In such a heredoc string, you can interpolate PHP variables, but you cannot include complex expressions (arithmetic expressions, function calls, ternary/coalescing operators, ...). Therefore, we first initialize the variables $name and $gender with the correct values, after which we use these variables in the heredoc syntax.

Form with get-self

Form with POST

  • Open course/form_post.php

 
 
 











 






















<?php
if ($_POST) {
    $name = !empty($_POST['name']) ? $_POST['name'] : 'Not specified';
    $gender = $_POST['gender'] ?? 'Not specified';
    echo <<<RESULTS
        <div class="margin-3">
            <p>Your inputs:</p>
            <ul> 
                <li>Name: <span class="text-primary"><b>$name</b></span></li>
                <li>Gender: <span class="text-primary"><b>$gender</b></span</li>
            </ul>
        </div>
    RESULTS;
} else {
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
    <div>
        <label for="name"><b>Name:</b></label>
        <input type="text" name="name" id="name" placeholder="Your name here">
    </div>
    <div>
        <label><b>Gender:</b></label>
        <input type="radio" name="gender" id="male" value="M">
        <label for="male">Male</label>

        <input type="radio" name="gender" id="female" value="F">
        <label for="female">Female</label >

        <input type="radio" name="gender" id="nonbinary" value="X">
        <label for="nonbinary">Non-binary</label>
    </div>

    <button type="submit" name="submit" class="btn-primary"><b>Submit</b></button>
</form>
<?php
}
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  • The form's method attribute is changed to POST and the associative array $_GET is replaced by $_POST

Form with post

REMARK

  • You can check the inputs sent with a POST request using Chrome's Developer Tools (F12 or Ctrl+Shift+I) and selecting/clicking Network -> form_post.php -> Headers -> Form Data

Inspect post

Last Updated: 9/22/2020, 4:30:43 PM