PHP - tutorial - 05 - forms

revision:


PHP - form handling

The PHP superglobals $_GET and $_POST are used to collect form-data.

example: POST method

Name:
E-mail:
code:
                <form action="welcome.php" method="post">
                    Name: <input type="text" name="name">< br>
                    E-mail: <input type="text" name="email">< br>
                    <input type="submit">
                </form>
            

example: GET method

Name:
E-mail:
code:
                <form action="welcome.php" method="post">
                    Name: <input type="text" name="name">< br>
                    E-mail: <input type="text" name="email">< br>
                    <input type="submit">
                </form>
            

Both GET and POST create an array (e.g. array( key1 => value1, 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, i.e as superglobals, 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.

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 (~ 2000 characters).
However, because the variables are displayed in the URL, it is possible to bookmark the page.

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

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).
There are also 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 a server.


PHP - form validation

The HTML form can contain various input fields: required and optional text fields, radio buttons, and a submit button.

text fields : the name, email, and website fields are text input elements, and the comment field is a textarea.

example: text fields - HTML code

Name:
E-mail:
Website:
Comment:
code:
                Name: <input type="text" name="name"><br>
                E-mail: <input type="text" name="email"><br>
                Website: <input type="text" name="website"><br>
                Comment: <textarea name="comment" rows="5" cols="40"></textarea><br>
            

radio buttons : gender fields are radio buttons.

example: radio buttons - HTML code

Female Male Other
code:
                <input type="radio" name="gender" value="female">Female
                <input type="radio" name="gender" value="male">Male
                <input type="radio" name="gender" value="other">Other
            

Form element:

example: form element - HTML code

code:
                <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                
                </form>
            

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script. It sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form.
The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like "<" and ">" with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.

security: the $_SERVER["PHP_SELF"] variable can be used by hackers! If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute. $_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.


PHP - required fields

Some fields in forms are required, meaning that these fields cannot be empty and must be filled out in the HTML form.

Field Validation Rules

Name Required. + Must only contain letters and whitespace

E-mail Required. + Must contain a valid email address (with @ and .)

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)

Gender Required. Must select one

example: required fields

Name: *

E-mail: *

Website:

Comment:

Gender: Female Male Other *

code:
                <div>
                    <?php
                        // define variables and set to empty values
                        $nameErr = $emailErr = $genderErr = $websiteErr = "";
                        $name = $email = $gender = $comment = $website = "";
                    ?>
                    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                        Name: <input type="text" name="name">
                        <span class="error">* <?php echo $nameErr;?></span>
                        <br><br>
                        E-mail:
                        <input type="text" name="email">
                        <span class="error">* <?php echo $emailErr;?></span>
                        <br><br>
                        Website:
                        <input type="text" name="website">
                        <span class="error"><?php echo $websiteErr;?></span>
                        <br><br>
                        Comment: <textarea name="comment" rows="5" cols="40"></textarea>
                        <br><br>
                        Gender:
                        <input type="radio" name="gender" value="female">Female
                        <input type="radio" name="gender" value="male">Male
                        <input type="radio" name="gender" value="other">Other
                        <span class="error">* <?php echo $genderErr;?></span>
                        <br><br>
                        <input type="submit" name="submit" value="Submit">
                    </form>
                    <?php
                        // define variables and set to empty values
                        $nameErr = $emailErr = $genderErr = $websiteErr = "";
                        $name = $email = $gender = $comment = $website = "";

                        if ($_SERVER["REQUEST_METHOD"] == "POST") {
                        if (empty($_POST["name"])) {
                            $nameErr = "Name is required";
                        } else {
                            $name = test_input($_POST["name"]);
                        }

                        if (empty($_POST["email"])) {
                            $emailErr = "Email is required";
                        } else {
                            $email = test_input($_POST["email"]);
                        }

                        if (empty($_POST["website"])) {
                            $website = "";
                        } else {
                            $website = test_input($_POST["website"]);
                        }

                        if (empty($_POST["comment"])) {
                            $comment = "";
                        } else {
                            $comment = test_input($_POST["comment"]);
                        }

                        if (empty($_POST["gender"])) {
                            $genderErr = "Gender is required";
                        } else {
                            $gender = test_input($_POST["gender"]);
                        }
                        }
                    ?>
                </div>
            

Error variables (e.g. $nameErr, $emailErr, $genderErr, and $websiteErr) can be added to the code.

These error variables will hold error messages for the required fields.
An if else statement for each $_POST variable checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function:

In the HTML form, a little script is added after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields).


PHP - email and URL validation

validate name:

The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.

example

        $name = test_input($_POST["name"]);
        if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
            $nameErr = "Only letters and white space allowed";
        }
    

validate email:

The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.

example

        $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $emailErr = "Invalid email format";
        }
    

validate URL:

The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.

example

        $website = test_input($_POST["website"]);
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
            $websiteErr = "Invalid URL";
        }
    

completed form

PHP Form Validation Example

* required field

Name: *

E-mail: *

Website:

Comment:

Gender: Female Male Other *

Your Input:





code:
                <div>
                    <style>
                        .error {color: #FF0000;}
                    </style>
                    <?php
                        // define variables and set to empty values
                        $nameErr = $emailErr = $genderErr = $websiteErr = "";
                        $name = $email = $gender = $comment = $website = "";

                        if ($_SERVER["REQUEST_METHOD"] == "POST") {
                        if (empty($_POST["name"])) {
                            $nameErr = "Name is required";
                        } else {
                            $name = test_input($_POST["name"]);
                            // check if name only contains letters and whitespace
                            if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
                            $nameErr = "Only letters and white space allowed";
                            }
                        }
                        
                        if (empty($_POST["email"])) {
                            $emailErr = "Email is required";
                        } else {
                            $email = test_input($_POST["email"]);
                            // check if e-mail address is well-formed
                            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $emailErr = "Invalid email format";
                            }
                        }
                            
                        if (empty($_POST["website"])) {
                            $website = "";
                        } else {
                            $website = test_input($_POST["website"]);
                            // check if URL address syntax is valid
                            if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
                            $websiteErr = "Invalid URL";
                            }    
                        }

                        if (empty($_POST["comment"])) {
                            $comment = "";
                        } else {
                            $comment = test_input($_POST["comment"]);
                        }

                        if (empty($_POST["gender"])) {
                            $genderErr = "Gender is required";
                        } else {
                            $gender = test_input($_POST["gender"]);
                        }
                        }

                        function test_input($data) {
                        $data = trim($data);
                        $data = stripslashes($data);
                        $data = htmlspecialchars($data);
                        return $data;
                        }
                        ?>
                        <h4>PHP Form Validation Example</h4>
                        <p><span class="error">* required field</span></p>
                        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
                            Name: <input type="text" name="name">
                            <span class="error">* <?php echo $nameErr;?></span>
                            <br><br>
                            E-mail: <input type="text" name="email">
                            <span class="error">* <?php echo $emailErr;?></span>
                            <br><br>
                            Website: <input type="text" name="website">
                            <span class="error"><?php echo $websiteErr;?></span>
                            <br><br>
                            Comment: <textarea name="comment" rows="5" cols="40"></textarea>
                            <br><br>
                            Gender:
                            <input type="radio" name="gender" value="female">Female
                            <input type="radio" name="gender" value="male">Male
                            <input type="radio" name="gender" value="other">Other
                            <span class="error">* <?php echo $genderErr;?></span>
                            <br><br>
                            <input type="submit" name="submit" value="Submit">  
                        </form>

                        <?php
                            echo "<h4>Your Input:</h4>";
                            echo $name;
                            echo "<br>";
                            echo $email;
                            echo "<br>";
                            echo $website;
                            echo "<br>";
                            echo $comment;
                            echo "<br>";
                            echo $gender;
                        ?>
                </div>