Module5 Forms
Module5 Forms
PHP PROGRAMMING
Module 5: Forms
Web Forms
‐ filter_var()
Forms are, by far, the most common way of interacting with PHP. As we mentioned before, it is
recommended that you have basic knowledge of HTML and CSS. If you don't, just head to the HTML
Wikibook (https://en.wikibooks.org/wiki/HTML) or W3School HTML Tutorial
(https://www.w3schools.com/html/) for a refresher.
Form Setup
To create a form the HTML tag <form> with the attributes action and method is specified as follows:
Once the user clicks "Submit", the form body is sent to the PHP script action.php for processing. The
values entered in all fields in the form are stored in the associative array variables $_GET or $_POST,
depending on the method used to submit the form.
The difference between the GET and POST methods is that the GET submits all the values in the URL
appended to the action URL an as query string parameters. While POST submits values transparently
through HTTP headers.
$_GET and $_POST are Superglobal arrays discussed in the next section.
Here is a simple form. Notice how it only contains HTML code and is saved with a .html file extension.
<!DOCTYPE html>
<html>
<body>
<h2>HTML Forms</h2>
<p>If you click the "Submit" button, the form-data will be sent to a
page called "action_page.php".</p>
</body>
</html>
Form Explanation:
id
action
method
The method used to send the information. Two methods are supported, POST and GET. POST is
the preferred method except for simple searches which generally use GET. Use with server‐side
languages.
fieldset
Form controls are normally contained in a fieldset element. Complex forms may have multiple
fieldsets. Fieldsets can contain other fieldsets.
legend
Each fieldset begins with a legend element. The content of the element is used as a title placed
in the border of the fieldset.
label for=""
A label for is a single form control. The value of the for attribute must match the id attribute of a
form control in the same form.
Various types of input controls. Supported types are ‐ submit, text, password, checkbox, radio,
reset, file, hidden, image and button. The name Attribute is used by the server to identify which
piece of data was entered in a given box on the form. The id attribute is used to match an input
with its label. The name and id attributes normally have identical values for text inputs but
different values for checkbox and radio inputs.
select
There is also a SELECT element for drop down lists and a TEXTAREA element for multi‐line text
input.
This simple example uses <br /> tags to force newlines between the different controls. A real‐world form
would use more structured markup to layout the controls neatly.
Superglobals
PHP has special built‐in variables of data type associative array that store server, script, form, session
information. Associative arrays elements are referenced with a string instead of an integer index value.
For example $GLOBAL[“varNume”];. These variables are available at all scopes of your script. Meaning
the variable is accessible in user defined functions or PHP include/required files without specifically
stating global $variable to access their values. These built‐in variables are known as Superglobals or
Autoglobals variables.
$GLOBALS
$_SERVER : A variable which holds information about headers, paths, and script locations.
$_REQUEST : Array of all the elements in the $_COOKIE, $POST, $_GET array
$_POST : Array of values input into a form using the POST method
$_GET : Array of values input into a form using the GET method
$_FILES
$_ENV
$_COOKIE
$_SESSION
$GLOBALS
$GLOBALS is a PHP Superglobal variable which can be called to access global variables anywhere in the
PHP script. PHP stores all global variables in an associative array called $GLOBALS[“string”]. The string in
$GLOBAL[] is the name of the variable that holds the variable value.
<!DOCTYPE html>
<html>
<body>
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
</body>
</html>
$_SERVER
$_SERVER is a PHP super global variable which holds information about the web server, the PHP script
executing and PHP engine being used. The $_SERVER[] variable can be useful to determine if either the
POST or GET method was used to submit a form or to create a form that calls back to itself.
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (such
as POST)
The example below shows how to use some of the elements in $_SERVER:
<!DOCTYPE html>
<html>
<body>
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
</body>
</html>
Method
Method is the <form> element attribute that defines how the form will be submitted to the server. The
method attribute can only be GET or POST. The difference between the GET and POST methods is that
GET method submits all the values in the URL appended to the action URL an as query string
parameters. The POST method submits values transparently through HTTP headers. A general rule of
thumb is if you are submitting sensitive data, use POST. POST forms usually provide more security
When the form is submitted to the server for processing, the form body is sent to the PHP script for
processing. All fields in the form are stored in either the Superglobal array $_GET or $_POST, depending
on the method used to submit the form. The form input fields name will be Superglobal array $_GET or
$_POST key and the user enter data will be the be Superglobal array value.
GET Method
As explained, any data sent via a PHP form using the GET method, will converted into values/data and
be added into a query string within URL known as URL Encoding. This URL encoding hold both action
script link separated by a ? and the encoded form field value/data separated by the & character.
http://www.asite.com/action.php?name=mary&email=mary@gmail.com&contact=1234567896
Side Note:
Filename: welcome_form.html
<!DOCTYPE html>
<html>
<title>HTML GET Method</title>
<body>
<h2>HTML Forms</h2>
<p>If you click the "Submit" button, the form-data will be sent to a page called
"welcome_get.php".</p>
</body>
</html>
Filename: welcome_get.php
<!DOCTYPE html>
<html>
<title>HTML GET Method</title>
<body>
<h2>HTML Forms</h2>
<?php
if( $_GET["name"] || $_GET["email"] || $_GET["contact"])
{
echo "Welcome: ". $_GET['name']. "<br />";
echo "Your Email is: ". $_GET["email"]. "<br />";
echo "Your Mobile No. is: ". $_GET["contact"];
}
?>
</body>
</html>
Within the same PHP script an if/else statement can be used to determine if the user has already filled in
the form and clicked submit. If this event has already occurred then the $_GET associative array will
have a value for each of the input fields (ie $_GET["name"]).
<input type="submit" name="submit" value="Submit">
<?php
if (isset($_GET["submit"])) {
// process the form contents...
}
echo $_SERVER['SCRIPT_NAME'];
?>
Now let’s take a look at an example of a PHP form using the POST method of storing user inputted data.
User submitted data in forms using the POST method are not transmitted to the server in the URL but in
an associated Superglobal array $_POST embedded in the HTML header. Each form input field name in
the form will automatically become a key in the $_POST Superglobal array and the user inputted data
will be the values of the $_POST Superglobal array that can be accessed by the action PHP script
$_POST[“fieldName”].
Form using the POST method also has no limit to the amount of data being transmitted to the server.
The POST method is the method required for file transfers or binary input to the server for server side
processing. For example, uploading images to Facebook to be added to your profile. All done via file
upload form and processed on the server side by PHP scripts. Developers prefer POST for sending form
data.
Filename:postsample.html
<!DOCTYPE html>
<html>
<head>
<title>HTML FORM POST</title>
</head>
<body>
<form action="postaction.php" method="post">
<label for="name">Name: </label>
<input type="text" name="name"></input><br/>
<label for="email">Email: </label>
<input type="text" name="email"></input><br/>
<label for="contact">Contact: </label>
<input type="text" name="contact"></input><br/>
<input type="submit" name="submit" value="Submit"></input>
</form>
</body>
</html>
Filename:postaction.html
<?php
// comment: checking if form has already been submitted with all fields completed
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["contact"])) {
echo "Welcome: ". $_POST['name']. "<br />";
echo "Your Email is: ". $_POST["email"]. "<br />";
echo "Your Mobile No. is: ". $_POST["contact"];
}
?>
Within the same PHP script, a condition statement has been defined to check if the $_POST associative
array has entries for name, email and contact. If these array entries exist, then print out “Welcome …. “.
<?php
//checking if form has already been submitted with all fields completed
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["contact"])) {
echo "Welcome: ". $_POST['name']. "<br />";
echo "Your Email is: ". $_POST["email"]. "<br />";
echo "Your Mobile No. is: ". $_POST["contact"];
}
?>
Username:
Password:
submit
The script used to process the loginForm.html file is login.php as defined by the action attribute in the
form tag.
Filename:login.php
<?php
$checkUsername = $_POST['username'];
$checkedPassword = $_POST['password'];
Form Validation
It is always recommended that ALL USER INPUT BE VALIDATED before that data is used in any way. By
validating the user input you are protecting your script and the server your site is being host on from
malicious attacks. A simple example of malicious code being entered is if a hacker entered
<script>location.href('http://www.abadsite.com')</script> in a form field of a guestbook. A guest book
normally display all guest entered greeting. Now with the malicious being display on the guestbook
comment page, all future guestbook visitors will automatically be redirected to www.abadsite.com
simple because the malicious JavaScript code has been entered form field and the PHP did not
validate/check if the user input is validate. This type of cyber attacked is called Cross‐Site Scripting (XSS).
Now let’s take a look at the sample login script, but now user input is being checked for special
characters with the PHP built‐in function htmlspecialchars().
Filename:login.php
<?php
$checkUsername = $_POST['username'];
$checkedPassword = $_POST['password'];
Now notice how the below code uses htmlspecialchars()in an attempt to clear any malicious HTML code.
Filename:login.php
<?php
$checkUsername = htmlspecialchars($_POST['username']);
$checkedPassword = htmlspecialchars($_POST['password']);
As you can see, $_POST is an array, with keys matching the names of each field in the form. For
backward compatibility, you can also refer to them numerically, but you generally shouldn't as this
method is much clearer.
Validating Forms
Let’s take a closer look at form validation. There are a few techniques for validating user input into a
form. The simplest methods is using the PHP's htmlspecialchars() function which attempts to replace
any HTML tags such as < > with the proper HTML code such as < and >.
Now the code is much safer and can prevents possible attackers from exploiting our code by injecting
HTML or Javascript code. If anyone attempts to enter code such as
<script>location.href('http://www.abadsite.com')</script> into a form field, what will be used after
using the htmlspecialchars() function is
<script>location.href('http://www.abadsite.com')</script>.
Now if you are expecting specific type of data entered by your users, you can attempt to validate even
further and check for a character pattern of the user inputted data to ensure it is in fact the input being
expected. Let check user input for an email address and user input for a date. We can start by removing
any unnecessary character from the variable and then remove any slashes.
If you are expecting a large amount of user input, it would be best to create a function that only validate
user input. Here is an example of such a function. Notice how this function take any data passed to it
and removed end of line, removes any slashed and then checks for any embedded HTML code and
replace it with HTML accepted characters for example < is <
<?php
function checkInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Let’s pass a user inputted field into our checkInput function.
$checkUsername = checkInput($_POST['username']);
Validate Other
There will be many specifically formatted fields in PHP that will need to be validate for security reasons
such as social security number, phone number, street address. Here we can take a quick look at some
such cases.
User Data
Once the user submitted data has been validated, what will the data be used for? The possibilities are
endless. Web forms are normally made with a specific purpose. Common form uses include shopping
carts, account creation, guestbook, survey, Canvas quizzes. One of the most widely used form are the
account registration form. The account information such as first name, last name, email address,
username, password and phone number is normally validated and then entered into a back end
database to be called in the future to authenticate accounts. Another common form is the email form.
The email form collects the user’s name and email address to then email information related to the
company directly to the user inbox.
HTML code below it into a plain text file and save it as contact.html. Notice how it only contains HTML
code and is saved with a .html file extension.
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
</form>
</body>
</html>
We could include the response in the PHP script (as shown before), but keeping it in an outside file
makes the script itself less complicated and the response page easier to edit and customize.
HTML code below it into a plain text file and save it as thanks.html
<!DOCTYPE html>
<html>
<head>
<title>Thank you Page</title>
</head>
<body>
</body>
</html>
Change the default "you@domain.com" recipient address inside the code to your own e‐mail address
(the one you wish to receive form results to)!
<?php
/* Set e‐mail recipient */
$myemail = "you@domain.com";
/* Let's prepare the message for the e‐mail with multi‐line string */
$message = "Hello!
Name: $yourname
E‐mail: $email
URL: $website
Comments:
$comments
End of message
";
/* Functions we used */
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if (strlen($data) == 0)
{
show_error("Empty Field");
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
</body>
</html>
<?php
exit();
}
?>
By using the $_SERVER["PHP_SELF"] super global variable, the file name of the currently executing script
is returned. That can be as the value for the action attribute in the form tag.
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
This form will then send the form data to itself for processing instead of being directed to secondary file.
For security purposing, it is recommended to pass the $_SERVER["PHP_SELF"] value to
htmlspecialchars() to convert any special characters to HTML entities.
If PHP_SELF is used in on a form, then a user can enter a slash (/) and then some Cross Site Scripting
(XSS) commands to execute. This is a security vulnerability. Cross‐site scripting (XSS) is a type of
computer security vulnerability typically found in Web applications. XSS enables attackers to inject
client‐side script into Web pages viewed by other users.
<!DOCTYPE html>
<html>
<head>
<title>HTML FORM POST</title>
</head>
<body>
<!-- comment: action attribute set to self -->
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<label for="name">Name: </label>
<input type="text" name="name"></input><br/>
<label for="email">Email: </label>
<input type="text" name="email"></input><br/>
<label for="contact">Contact: </label>
<input type="text" name="contact"></input><br/>
<input type="submit" name="submit" value="Submit"></input>
</form>
<?php
// comment: checking if form has already been submitted with all fields completed
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["contact"])) {
echo "Welcome: ". $_POST['name']. "<br />";
echo "Your Email is: ". $_POST["email"]. "<br />";
echo "Your Mobile No. is: ". $_POST["contact"];
}
?>
</body>
</html>
Sample Code: Single PHP script using function and condition to display and process the form:
<!DOCTYPE html>
<html>
<head>
<title>Single PHP File Form</title>
</head>
<body>
<?php
$states = array('AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA',
'HI', 'ID', 'IL', 'IN', 'IA',
'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH',
'NJ', 'NM', 'NY', 'NC', 'ND',
'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV',
'WI', 'WY');
function validate_form() {
$error = array();
if (!in_array($_POST["from_state"], $GLOBALS['states'])) {
$error[] = "Please select a valid state for the From address."; //Add to Error
List
}
$fromzip = $_POST["from_zip"];
if (!preg_match("/^[0-9]{5}([- ]?[0-9]{4})?$/", $fromzip)) {
$error[] = "Enter a valid zip code for the From address";
}
if (!in_array($_POST["from_state"], $GLOBALS['states'])) {
$error[] = "Please select a valid state for the To address."; //Add to Error
List
}
$tozip = $_POST["to_zip"] ;
if (!preg_match("/^[0-9]{5}([- ]?[0-9]{4})?$/", $tozip)) {
$error[] = "Enter a valid zip code for the To address";
}
if ($_POST['weight'] > 150) {
$error[] = "Too much weight";
}
if (($_POST['height'] > 36) || ($_POST['width'] > 36) || ($_POST['depth'] > 36)) {
$error[] = "Too big";
}
if(empty($error)) {
process_form();
}
return $error;
} // end validate_form()
function process_form() {
print "Hi " . $_POST['from_name'] . ", your package is ready<br>";
print "Your box's size is " . $_POST['height'] . "in" . "x" . $_POST['width'] .
"in" . "x" . $_POST['depth'] . "in" . "<br>";
print "Your box weighs " . $_POST['weight'] . "lbs" . "<br>";
print "Would you like to ship another package?" . "<br>". "<br>";
} // end process_form()
?>
</body>
</html>
Sticky Forms
When submitting forms, it is commonly for users to submit the form incorrectly. The user is either
entering invalid formatted data or leaving a field empty. Once the user submits the form, it is normally
for an error message to appear stating why the form was submitted incorrect. But the fields they did
enter correctly is gone. Making the user reenter all the data again. Sticky forms, are form specifically
coded to reenter the valid text the user did enter when prompting the user to correct the incorrectly
entered fields. Notice the HTML input attribute value is set to a PHP echo statement:
<input type="text" name="fullname" value="<?php echo $fullname; ?>">
By using multiple PHP escape tags, the user entered data can be entered back into the form.
Filename: stickyform.php
<?php
$fullname = "";
$email = "";
$text = "";
if(isset($_POST['fullname']) && $_POST['fullname'] != "") {
$fullname = $_POST['fullname'];
}
if(isset($_POST['email']) && $_POST['email'] != "") {
$email = $_POST['email'];
}
if(isset($_POST['feedback']) && $_POST['feedback'] != "") {
$text= $_POST['feedback'];
}
?>
<html>
<h1>Customer Feedback</h1>
<p1>Please tell us what you think</p1><br><br>
<p1>Your feedback:</p1><br>
<textarea rows="5" cols="50" name="feedback"><?php echo $text;?>
</textarea><br><br>