Working With Forms
Working With Forms
Working With Forms
Forms:
A form is an HTML tag that contains graphical user interface items such as input box,
check boxes radio buttons etc.
Forms come in handy when developing flexible and dynamic applications that accept
user input and also can be used to edit already existing data from the database
Forms are used to get input from the user and submit it to the web server for
processing.
The query string (name/value pairs) is sent in the HTTP message body of a POST request.
POST requests are never cached
POST requests do not remain in the browser history
POST requests cannot be bookmarked
POST requests have no restrictions on data length
It has the following syntax.
<?php
$_POST['variable_name'];
?>
HERE,
HERE,
History Parameters remain in browser history Parameters are not saved in browser history
Restrictions on data length Yes, when sending data, the GET method No restrictions
adds the data to the URL; and the length of a
URL is limited (maximum URL length is 2048
characters)
Restrictions on data type Only ASCII characters allowed No restrictions. Binary data is also allowed
Security GET is less secure compared to POST POST is a little safer than GET because the
because data sent is part of the URL parameters are not stored in browser history
or in web server logs
Never use GET when sending passwords or
other sensitive information!
Visibility Data is visible to everyone in the URL Data is not displayed in the URL
The PHP $_GET and $_POST variables are used to retrieve information from forms, like
user input.
We will use the PHP isset function to check if the form values have been filled in the
$_POST array and process the data.
Registration form that include the PHP code that processes the data:
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
</head>
<?php if (isset($_POST['form_submitted'])): ?> //this code is executed when the form is submitted
<h2>Registration Form</h2>
First name:
<input type="text" name="firstname">
</form>
<?php endif; ? >
</body>
</html>
HERE,
<?php if (isset($_POST['form_submitted'])): ?> checks if the form_submitted
hidden field has been filled in the $_POST[] array and display a thank you and
first name message.
If the form_fobmitted field hasn’t been filled in the $_POST[] array, the form is
displayed.
Super Global variables
$_GET Variable: The $_GET variable is an array of variable names and values sent
by the HTTP GET method.
$_POST Variable: The $_POST variable is an array of variable names and values
sent by the HTTP POST method.
$_SERVER: is a PHP super global variable which holds information about headers,
paths, and script locations.
The example below shows how to use some of the elements in $_SERVER:
<?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'];
?>
OUTPUT
/website/rand.php
localhost
localhost
Element/Code Description
$_REQUEST: is a PHP super global variable which contains submitted form data, and all cookie
data.
In other words, $_REQUEST is an array containing data from $_GET, $_POST, and $_COOKIE.
You can access this data with the $_REQUEST keyword followed by the name of the form field, or cookie,
like this:
$_REQUEST['firstname']
EXAMPLE
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
Querystring
The information can be sent across the web pages. This information is called query
string.
This query string can be passed from one page to another by appending it to the
address of the page.
You can pass more than one query string by inserting the & sign between the query
strings.
A query string can contain two things: the query string ID and its value.
Whether you passed the query string by using GET or POST method, it is stored in
$_REQUEST variable..
If you want to use $_GET variable to access the query string the form method need
to be GET. Also you can use $_POST variable to get the query string if the form
method is POST.
In the following example, the query strings username and email(the names of
textboxes) are passed from a page called login.php to another page called
welcome.php when you click the submit button.
Login.php:
<html>
<head>
<title>Login form</title>
</head>
<body>
<form action="welcome.php" method=”get”>
<table>
<tr>
<td>User name:</td><td> <input type="text" name="username" ></td>
</tr>
<tr>
<td>E-mail: </td><td><input type="text" name="email" ></td>
</tr>
<tr>
<td><input type="submit" name="sub" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
welcome.php:
<?php
echo "<strong>Welcome ".$_GET['username']. "!</strong><br/>"; echo
"Please remember this e-mail: ".$_GET['email']. " for later use.";
?>
Imagine you have a URL:
rand.php?name=shubham&age=21
Then the query string is:
?name=shubham&age=21
In this case, the query consists of two parts: a key name with value shubham, and a key age
with value 21.
You can access the value of the query string keys using this code:
$_GET['name'];
EXAMPLE
<?php
echo '<a href="rand.php?name=;shubham&age=21"> Query Strings </a>';
if(isset($_GET['name'])) {
echo $_GET['name'];
}
?>
Different ways in PHP to retrieve the query string and its parameter values from a URL.
We'll be using the following string for all the examples to follow:
rand.php?name=shubham&age=21
When we have all the key/value pairs in a single string, we can use the parse_str
function to convert the key/value pairs to an array:
// method #1
parse_str($_SERVER['QUERY_STRING'], $output1);
print_r($output1);
// method #2
parse_str(parse_url('rand.php?name=shubham&age=21',PHP_URL_QUERY),
$output2);
print_r($output1);
HTML Form Controls and PHP
Simple search engine
We will design a simple search engine that uses the PHP_GET method as the form
submission type. For simplicity’s sake, we will use a PHP If statement to determine the
output.
We will use the same HTML code for the registration form above and make minimal
modifications to it.
<html>
<head>
<title>Simple Search Engine</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
Term:
<input type="text" name="search_term">
<br>
</form>
<?php endif; ?>
</body>
</html>
Note the URL has displayed the value of search_term and form_submitted.
We will modify the registration form code and include a check button that allows
the user to agree to the terms of service.
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
First name:
<input type="text" name="firstname">
</form>
<?php endif; ?>
</body>
</html>
Note the Agree to Terms of Service checkbox has not been selected.
Click on back to the form link and then select the checkbox
Form Validation
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
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
When the form is submitted, the form data is sent with method="post".
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.
So, the $_SERVER["PHP_SELF"] 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.
Warning!
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.
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.
Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:
<form method="post" action="test_form.php">
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
This code adds a script tag and an alert command. And when the page loads, the JavaScript code will
be executed (the user will see an alert box). This is just a simple and harmless example how the
PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can redirect the
user to a file on another server, and that file can hold malicious code that can alter theglobal variables or
submit the form to another address to save the user data, for example.
The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries
to exploit the PHP_SELF variable, it will result in the following output:
<form method="post" action="test_form.php/"><script>alert('hacked')</script& gt;">
When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:
<script>location.href('http://www.hacked.com')</script>
will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP
trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
The next step is to create a function that will do all the checking for us (which is much moreconvenient
than writing the same code over and over again).
Now, we can check each $_POST variable with the test_input() function, and the script looks like this:
Example
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);return
$data;
}
?>
In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and
$websiteErr. These error variables will hold error messages for the required fields. We have also added
an if else statement for each $_POST variable. This 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:
<?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"]);
}
}
?>
Example
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
</form>
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
The preg_match() function searches a string for pattern, returning true if the pattern exists,
and false otherwise.
In the code below, if the e-mail address is not well-formed, then store an error message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular expressionalso
allows dashes in the URL). If the URL address syntax is not valid, then store an error message:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-
a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
Then, we also need to show which radio button that was checked. For this, we must manipulatethe
checked attribute (not the value attribute for radio buttons):
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
Maintaining State
The Web Server does not remember your past transactions. If you have a sequence of
transactions where the action of the present transaction is dependent on a past
transaction then the present transaction must have some "memory" of the past
transaction.
There must be some mechanism in place to transfer information from the past
transaction to the present.
This transfer of information can be done in 3 ways:
Hidden Variables
Cookies
State Files
Hidden Variables
Hidden variables are name-value pairs that are embedded in a form that can be
checked by the script processing form data on the server side.
As the name implies hidden variables are not displayed when the form is rendered
on the client side.
EXAMPLE An order form is displayed, once you place the order a confirmation
page is displayed, when you confirm the order a thank-you page is displayed.
A hidden variable page keeps track of whichpage is to be displayed.
Here is the application logic:
if ($_POST["page"] == "confirm")
confirmPage();
elseif ($_POST["page"] == "order")
orderPage();
else
orderForm();
When the script is first called the variable page is not set and hence the function
orderForm() is called. After that the confirmPage() function is called and finally the
function orderPage().
function confirmPage()
{
$size = $_POST["size"];
$script =
$_SERVER['PHP_SELF']; print
<<<PAGE2
<html>
<head>
<title> Confirm Order </title>
</head>
<body>
<p>
You ordered a $size pizza. Please confirm.
</p>
<p>
<form method = "post" action = "$script">
<input type = "hidden" name = "page" value = "order" />
<input type = "submit" value = "Confirm Order" />
</form>
</p>
</body>
</html>
PAGE2;
}
function orderPage()
{
print <<<PAGE3
<html>
<head>
<title> Place Order </title>
</head>
<body>
<p>Thank you. Your order has been placed.</p>
</body>
</html>
PAGE3;
}
?>
Cookies
A cookie is a small piece of data in the form of a name-value pair that is sent by a
Web server and stored by the browser on the client machine.
This information is used by the application running on the server side to customize
the web page according to the past history of transactions from that client machine.
The application program on the server side reads the cookies and tailors the web
page accordingly.
It may reset the cookies according to the present transaction.
A cookie is created with the setcookie() function.
Syntax : setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
A transient cookie is there just for the session. A persistent cookie can exist for a long
time (order of years). The application program sets the time to live for the cookie. One
way of deleting a cookie is to set its time to live to a time in the past.
A cookie is a name-value pair. In its simplest form to set a transient cookie the
function setcookie() is used with the name-value pair as parameters:
setcookie ("some_name", "some_value");
To set a permanent cookie the expiration time must be given. One way is to read the
current time and then add an increment to it in seconds. For example to set a cookie
that lasts for a year the following command will work:
setcookie ("some_name", "some_value", time()+3600*24*365);
The setcookie() function must be called before any printed output occurs. The
cookie must be written as part of the HTTP header.
All cookies from that url are sent back to the server when the browser requests a web
page. The associative array $_COOKIE holds all the name value pairs. To read the
value for a particular cookie do:
$value = $_COOKIE["some_name"];
State Files
In PHP name-value pairs can be stored in state files on the server side. A sessioncan be
started by using the command
session_start();
before making any printed output. A unique session id is generated. The script need
not know the id but its value can be retrieved from
$id = session_id();
Session ids can be passed as hidden variables or stored as cookies between
transactions. To close a session do
session_destroy();
This code uses session variables to generate an online quiz, keep track of the
number of questions asked and the score.
<?php
session_start();
if (!session_is_registered("number"))
{
$_SESSION["number"] = 0;
$_SESSION["answer"] = 0;
$_SESSION["correct"] = 0;
$_SESSION["question"] = "";
}
$total_number = 10;
print <<<TOP
<html>
<head>
<title> Arithmetic Quiz </title>
</head>
<body>
<h3> Arithmetic Quiz </h3>TOP;
$number = $_SESSION["number"];
$answer = $_SESSION["answer"];
$correct = $_SESSION["correct"];
$question = $_SESSION["question"];
if ($number == 0)
{
print <<<FIRST
<p> You will be given $total_number questions in this quiz. <br /><br/>Here
is your first question: <br /><br />
</p>
FIRST;
}
if ($number > 0)
{
if ($_POST["answer"] == $answer)
{
$correct++;
$_SESSION["correct"] = $correct;
print <<<CORRECT
Yes you are correct: $question $answer. <br /><br />
CORRECT;
}
else
{
print <<<WRONG
Sorry, that is not correct: $question $answer
<br /><br />
WRONG;
}
}
print <<<BOTTOM
</body>
</html>
BOTTOM;
?>