In the earlier chapters, we learned about forms, such as what forms are, how we can validate them, and how we can improve the look and feel of them, but what is the use of forms until they store information? In this chapter, we will learn how to store the user's input data into a database using PHP and MySQL.
In this chapter, we will cover the following topics:
PHP, which is also used as a general-purpose programming language, is basically a server-side scripting language, which is designed for web development. With a PHP processor module, PHP code is interpreted by a web server resulting in the generation of a web page.
Rather than calling an external file to process data, PHP commands can be embedded directly into the HTML code. It can be used for standalone graphical applications and can be deployed on most of the web servers for almost every operating system and platform.
All variables in PHP are case-sensitive, but user-defined functions, classes, and keywords such as if, else, while, echo, and many more are case-insensitive.
On the server, first a PHP script is executed and then the HTML result is sent back to the browser.
Through an HTML form, the ability of PHP to easily manipulate the information submitted by the user is one of the reasons why it is popular.
To use PHP, we have to perform the following steps:
The default extension for a PHP file is .php
and a PHP script starts with <?php
and ends with ?>
.
<?php // PHP script ?>
Including some PHP scripting code, a PHP file normally contains HTML tags. A semicolon is used to terminate PHP statements, and we do not need to use a semicolon to terminate the last line of a PHP block.
The $_GET
and $_POST
PHP superglobals (built-in variables that are always available in all scopes) are used to collect the form data which is submitted by the user on clicking on the Submit button.
In the GET
method, the information from a form is visible to everyone; for example, all the variable names and the values are displayed in the URL. Moreover, using the GET
method has limits on the amount of information that can be sent, which varies from browser to browser.
This method is useful when we need to bookmark the web page because the variables are displayed in the URL.
We cannot use the GET
method for sending sensitive data, such as passwords or credit card information.
The following code is a simple HTML page:
<html> <body> <form action="example.php" method="get"> Name: <input type="text" name="name"><br> Age: <input type="text" name="age"><br> <input type="submit"> </form> </body> </html>
When a user fills the preceding form and clicks on the Submit button, the form data is sent for processing to a PHP file named example.php
. The form data is sent with method="get"
.
The example.php
file will look similar to the following code:
<html> <body> Hello! <?php echo $_GET["name"]; ?>!<br> You are <?php echo $_GET["age"]; ?> years old. </body> </html>
The information from a form is not visible to everyone in the POST
method;for example, within the body of the HTTP request, all the variable names and the values are embedded. Moreover, using the POST
method has no limitation on the amount of information to send.
This method is not useful when we need to bookmark the web page because the variables are not displayed in the URL.
Moreover, while uploading the files to the server, the POST
method also supports advanced functionality such as support for multipart binary input.
We can use the POST
method for sending sensitive data, such as passwords or credit card information.
The following code is a simple HTML page:
<html> <body> <form action="example.php" method="post"> Name: <input type="text" name="name"><br> Age: <input type="text" name="age"><br> <input type="submit"> </form> </body> </html>
When a user fills the preceding form and clicks on the submit button, the form data is sent for processing to a PHP file named example.php
. The form data is sent with method="post"
.
The example.php
file looks like this:
<html> <body> Hello! <?php echo $_POST["name"]; ?>!<br> You are <?php echo $_POST["age"]; ?> years old. </body> </html>
Both the GET
and POST
methods populate the $_GET
and $_POST
arrays respectively. As these are superglobals, regardless of scope, they are always accessible, and they can be accessed from any class, function, or file without having to do anything special. These arrays are described as follows:
The filter
method filters data by either validating or sanitizing the input fields. It plays a very important role and is useful when the data source contains unknown data, such as custom input or user supplied input.
For example, data entered through an HTML form in cases, such as survey forms, and new registrations.
There are two main types of filtering:
Filtering of input data is one of the major concerns when it comes to security issues. External data includes input data from the user, cookies, web service data, or database query results. As all web forms and applications depend on external input so with filtering the input data we can be sure that our application gets valid input from the user.
The following filter
functions can be used to filter a variable:
filter_var_array()
: It gets multiple variables with the same or different filtersfilter_id()
: It returns the ID number of a specified filterfilter_var()
: It filters a single variable with a specified filterfilter_input()
: It gets one input variable by the name and optionally filters itfilter_has_var()
: It checks whether a variable of a specified input type exists or notfilter_input_array()
: It gets several input variables and filters them with the same or different filtersfilter_list()
: It returns a list of all the supported filtersIn the following example, we are validating an integer using the filter_var()
function:
<?php $int = 'g819'; if(!filter_var($int, FILTER_VALIDATE_INT)) { echo("Entered integer is invalid"); } else { echo("Entered integer is valid"); } ?>
In the preceding code, the FILTER_VALIDATE_INT
filter is used to filter the variable. Since the integer is not valid, the output of the preceding code will be Integer is invalid, but if we try with a variable that is an integer, such as 819, the output will be Integer is valid.
The filter
method is used to validate the user input data. It returns the value true on success and false on failure.
Strict format rules are followed for validating the IP address, URL, variables, or e-mail type.
Now, in the following example, we will validate an input field of a form. Before we start, we will first check the presence of the required input data. Then, using the filter_var()
function, we will validate the input data.
<?php if(!filter_has_var($_GET["url"l)) { echo("Input type is not present"); } else { if (!filter_var($_GET["url"l, FILTER_VALIDATE_URL)) { echo "Entered URL is invalid"; } else { echo "Entered URL is valid"; } } ?>
In the preceding example, an input url
is sent using the GET
method. It first checks if an input email
variable of the GET
type is present or not. When the input variable is present, it validates the URL.
The main purpose of sanitizing is to allow or not to allow the specified characters in the string. It always returns a string value. It does not follow any data format rules.
In the following example, we will validate an input field of a form. Before we start, we will first check the presence of the required input data. Then, using the filter_var()
function, we will sanitize the input data.
<?php if(!filter_has_var(($_POST['string'l)) { echo("Input type is not present"); } else { $string = filter_var($_POST['string'l, FILTER_SANITIZE_STRING); } ?>
In the preceding example, an input string
is sent using the POST
method. It first checks if an input string
variable of the POST
type exists. When the input variable is present, it validates the string.
When the user inputs a bad input string such as MasteringååHTML5ååForms
, after sanitizing, the same string will look like MasteringHTML5Form
.
Using the FILTER_CALLBACK
filter, it is possible to call a user-defined function and use it as a filter. We can get full control of data filtering using this.
In a similar manner as when specifying an option, the function which we want to use to filter is specified.
We can use an existing PHP function or also create our own user-defined functions.
In the following example, we will create a user-defined function to replace all *
symbols with whitespaces:
<?php function towhitespace($string) { return str_replace("*", " ", $string); } $string = "Converting*To*Whitespace*Characters"; echo filter_var($string, FILTER_CALLBACK, array("options"=>"towhitespace")); ?>
The output of the preceding code is:
In the preceding example, at any place in a string and no matter how many times, all the *
symbols are replaced with the whitespace characters.
In the preceding code, we first created a function to replace all the *
symbols with whitespaces. Then, the filter_var()
function is called with the FILTER_CALLBACK
filter and an array containing the function.
Nowadays, almost every web form consists of more than one input field such as the registration page. When a form consists of more than one input field, calling filter_var()
or filter_input()
functions for every input field to validate or sanitize not only increases the size of the code but also the complexity. The remedy for this is to use the filter_var_array()
or filter_input_array()
functions.
In the following example, we will validate two input fields of a form. We will use the filter_var_array()
function to filter these variables and use the POST
method. The input is in the form of age and e-mail address.
<?php $filters = array ( "age" => array ( "filter"=>FILTER_VALIDATE_INT, "options"=>array ( "min_range"=>1, "max_range"=>99 ) ), "email"=> FILTER_VALIDATE_EMAIL ); $output = filter_var_array($_POST, $filters); if (!$output["age"]) { echo("Entered age must be between 1 and 99"); } elseif(!$output["email"]) { echo("Entered email is invalid"); } else { echo("Entered inputs are valid"); } ?>
In the preceding example, the input fields are sent using the POST
method. Here, an array is set, which contains the name of the input variables, such as age
and email
. We have also used the filters on these input variables.
First, we call the
filter_var_array()
function with the POST
method input variables and the array we had set. Then, we validated the age
and email
variables in the $output
variable for the invalid inputs.
The second parameter of the filter_input_array()
or filter_var_array()
function can be a single filter ID or an array. All the values in the input array are filtered by the specified filter when the parameter is a single filter ID.
The following rules must be followed if the parameter is an array:
email
or age
input variable3.140.195.28