Nothing Special   »   [go: up one dir, main page]

Working With Forms

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

UNIT 3

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 diagram below illustrates the form handling process.

Submitting the form data to the server


 The action attribute of the form specifies the submission URL that processes the
data.
 The method attribute specifies the submission type.
PHP POST method
 This is the built in PHP super global array variable that is used to get values
submitted by HTTP POST method.
 The array variable can be accessed from any script in the program; it has a global
scope.
 This method is ideal when you do not want to display the form post values in the
URL.
 A good example of using post method is when submitting login details to the server.

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,

 “$_POST[…]” is the PHP array


 “'variable_name'” is the URL variable name.

PHP GET method


 This is the built in PHP super global array variable that is used to get values
submitted by HTTP GET method.
 The array variable can be accessed from any script in the program; it has a global
scope.
 This method displays the form values in the URL.
 It’s ideal for search engine forms as it allows the users to book mark the results.

 The query string (name/value pairs) is sent in the URL of a GET request.
 GET requests can be cached
 GET requests remain in the browser history
 GET requests can be bookmarked
 GET requests should never be used when dealing with sensitive data
 GET requests have length restrictions 
 GET requests should be used only to retrieve data

• It has the following syntax.


<?php
$_GET['variable_name'];
?>

HERE,

 “$_GET[…]” is the PHP array


 “'variable_name'” is the URL variable name.
GET vs POST Methods
GET POST

BACK button/Reload Harmless Data will be re-submitted (the browser


should alert the user that the data are about
to be re-submitted)

Bookmarked can be bookmarked cannot be bookmarked

cached can be cached Not cached

Encoding type application/x-www-form-urlencoded application/x-www-form-urlencoded or


multipart/form-data. Use multipart encoding
for binary data

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

Form handling in PHP

The PHP $_GET and $_POST variables are used to retrieve information from forms, like
user input.

GET v/s POST


FORM SUBMISSION POST METHOD

< :f o r m actio n = "registration_:form.php "


Fir s t name: < input t yp e = "text" nam ~ e!!l!!!
= "l'l'!l--!!!!'!!!!!'!l!!!"!!!"!!!!'!!!!i'!III/':"'..
L a s t name : < input t y pe= "text" name = "lastname" >
<br >
< input t y pe = "hidden" name = ":form submitted" v alue = "1" />
< input t y pe = "subrni t" v alue = "Submit">
</ :f o rm>

Submission URL does not show form values

G localhost/t uttis/registration_form .php


Processing the registration form data
 The registration form submits data to itself as specified in the action attribute of theform.
When a form has been submitted, the values are populated in the $_POST super global
array.

 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>Thank You <?php echo $_POST['firstname']; ?> </h2>

<p>You have been registered as


<?php echo $_POST['firstname'] . ' ' . $_POST['lastname']; ?>
</p>

<p>Go <a href="/registration_form.php">back</a> to the form</p>


<?php else: ?>

<h2>Registration Form</h2>

<form action="registration_form.php" method="POST">

First name:
<input type="text" name="firstname">

<br> Last name:


<input type="text" name="lastname">

<input type="hidden" name="form_submitted" value="1" />

<input type="submit" value="Submit">

</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

Warning: Undefined array key "HTTP_REFERER" in C:\xampp\htdocs\website\rand.php on line 12

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)


Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0
/website/rand.php
The following table lists the most important elements that can go inside $_SERVER:

Element/Code Description

$_SERVER['PHP_SELF'] Returns the filename of the currently executing


script

$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway


Interface (CGI) the server is using

$_SERVER['SERVER_ADDR'] Returns the IP address of the host server

$_SERVER['SERVER_NAME'] Returns the name of the host server (such as


www.w3schools.com)

$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as


Apache/2.2.24)

$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information


protocol (such as HTTP/1.1)

$_SERVER['REQUEST_METHOD'] Returns the request method used to access the


page (such as POST)

$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request


(such as 1377687496)

$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed


via a query string

$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current


request

$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the


current request (such as utf-8,ISO-8859-1)

$_SERVER['HTTP_HOST'] Returns the Host header from the current request

$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page


(not reliable because not all user-agents support
it)

$_SERVER['HTTPS'] Is the script queried through a secure HTTP


protocol

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is


viewing the current page

$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is


viewing the current page

$_SERVER['REMOTE_PORT'] Returns the port being used on the user's


machine to communicate with the web server

$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently


executing script
$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN
directive in the web server configuration file (if
your script runs on a virtual host, it will be the
value defined for that virtual host) (such as
someone@w3schools.com)

$_SERVER['SERVER_PORT'] Returns the port on the server machine being


used by the web server for communication (such
as 80)

$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name


which are added to server-generated pages

$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current


script

$_SERVER['SCRIPT_NAME'] Returns the path of the current script

$_SERVER['SCRIPT_URI'] Returns the URI of the current page

 $_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>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?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

Retrieving The Query String


 Query String Of Current URL:
 Using $_SERVER['QUERY_STRING'] in PHP we can get the full query string
from the current URL.
 For example:
echo $_SERVER['QUERY_STRING'];
//Output: name=;shubham&age=21

 Query String From A String


 To retrieve the query string from a string we can use the parse_url function.
 For example:
echo parse_url('rand.php?name=;shubham&age=21', PHP_URL_QUERY);
//Output: name=;shubham&age=21

 Query String Parameters As An Array


 Using $_GET array in PHP we can directly access any key/value pair in the
current URL.
 For example:
echo $_GET['name'];
//Output: shubh
Parsing A Query String
 The parse_str() function is a built-in function in PHP which parses a query string into
variables.
 The string passed to this function for parsing is in the format of a query string passed
via a URL.
 Parameters: This function accepts two parameters as shown in the above syntax out
of which the first parameter must be supplied and the second one is optional.
 All of these parameters are described below:
 $string: It specifies the string to parse.
 $array: This is an optional parameter which specifies the name of an array to store
the variables. This parameter indicates that the variables will be stored in an array.

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>

<?php if (isset($_GET['form_submitted'])): ?>

<h2>Search Results For <?php echo $_GET['search_term']; ?> </h2>


<?php if ($_GET['search_term'] == "GET"): ?>
<p>The GET method displays its values in the URL</p>

<?php else: ?>


<p>Sorry, no matches found for your search term</p>

<?php endif; ?>

<p>Go <a href="/search_engine.php">back</a> to the form</p>

<?php else: ?>

<h2>Simple Search Engine - Type in GET </h2>

<form action="search_engine.php" method="GET"> Search

Term:
<input type="text" name="search_term">
<br>

<input type="hidden" name="form_submitted" value="1" />

<input type="submit" value="Submit">

</form>
<?php endif; ?>
</body>
</html>

View the above page in a web browser

The following form will be shown

Type GET in upper case letter then click on submit button.

The following will be shown


The diagram below shows the URL for the above results

Note the URL has displayed the value of search_term and form_submitted.

Working with check boxes, radio buttons


If the user does not select a check box or radio button, no value is submitted, if the
user selects a check box or radio button, the value one (1) or true is 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>

<?php if (isset($_POST['form_submitted'])): ?>

<?php if (!isset($_POST['agree'])): ?>

<p>You have not accepted our terms of service</p>

<?php else: ?>

<h2>Thank You <?php echo $_POST['firstname']; ?></h2>

<p>You have been registered as


<?php echo $_POST['firstname'] . ' ' . $_POST['lastname']; ?>
</p>

<p> Go <a href="/registration_form2.php">back</a> to the form</p>

<?php endif; ?>

<?php else: ?>


<h2>Registration Form</h2>

<form action="registration_form2.php" method="POST">

First name:
<input type="text" name="firstname">

<br> Last name:


<input type="text" name="lastname">

<br> Agree to Terms of Service:


<input type="checkbox" name="agree">
<br>

<input type="hidden" name="form_submitted" value="1" />

<input type="submit" value="Submit">

</form>
<?php endif; ?>
</body>
</html>

View the above form in a browser

Fill in the first and last names

Note the Agree to Terms of Service checkbox has not been selected.

Click on submit button

You will get the following results

Click on back to the form link and then select the checkbox
Form Validation

The validation rules for the form above are as follows:

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


Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea.
The HTML code looks like this:
Name: <input type="text" name="name"> E-
mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>

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

The Form Element


The HTML code of the form looks like this:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

When the form is submitted, the form data is sent with method="post".

What is the $_SERVER["PHP_SELF"] variable?

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.

What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters into HTML entities.


This means that it will replace HTML characters like < and > with &lt; and &gt;. This
prevents attackers from exploiting the code by injecting HTML or Javascript code
(Cross-site Scripting attacks) in forms.
Big Note on PHP Form Security

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.

Assume we have the following form in a page named "test_form.php":


<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

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

In this case, the above code will be translated to:


<form method="post" action="test_form.php/"><script>alert('hacked')</script>

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.

How To Avoid $_SERVER["PHP_SELF"]


Exploits?
$_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.

The form code should look like this:


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

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/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script& gt;">

The exploit attempt fails, and no harm is done!

Validate Form Data With PHP


The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.

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:

&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;

The code is now safe to be displayed on a page or inside an e-mail.We

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).

We will name the function test_input().

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"]);
}
}
?>

PHP - Display The Error Messages


Then in the HTML form, we add a little script 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):

Example
<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 - Validate Name


The code below shows a simple way to check if the name field only contains letters and
whitespace. If the value of the name field is not valid, then store an error message:

$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.

PHP - Validate E-mail


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

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";
}

PHP - Keep The Values in The Form


To show the values in the input fields after the user hits the submit button, we add a little
PHP script inside the value attribute of the following input fields: name, email, and
website. In the comment textarea field, we put the script between
the <textarea> and </textarea> tags. The little script outputs the value of
the $name, $email, $website, and $comment variables.

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):

Name: <input type="text" name="name" value="<?php echo $name;?>">

E-mail: <input type="text" name="email" value="<?php echo $email;?>">

Website: <input type="text" name="website" value="<?php echo $website;?>">

Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>

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().

Here is how the transaction sequence works.

This is the actual code.


<?php
if ($_POST["page"] == "confirm")
{
confirmPage ();
}
elseif ($_POST["page"] == "order")
{
orderPage();
}
else
{
orderForm();
}
function orderForm()
{
$script = $_SERVER['PHP_SELF'];
print <<<PAGE1
<html>
<head>
<title> Pizza Order Form </title>
</head>
<body>
<h3> Pizza Order Form </h3>
<form method = "post" action = "$script">
<p>
<label> Large </label>
<input type = "radio" name = "size" value = "large" />
<label> Medium </label>
<input type = "radio" name = "size" value = "medium" />
<label> Small </label>
<input type = "radio" name = "size" value = "small" />
<input type = "hidden" name = "page" value = "confirm" />
</p>
<p>
<input type = "submit" value = "Place Order" />
</p>
</form>
</body>
</html>
PAGE1;
}

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();

The name-value pairs are stored in an array called $_SESSION. To register a


name-value pair do:
$_SESSION["some_name"] = some_value;
To extract or retrieve the value from a session variable:
$value = $_SESSION["some_name"];

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;
}
}

if ($number >= $total_number)


{
print <<<FINAL_SCORE
Your final score is $correct correct out of $total_number. <br /><br />
Thank you for playing. <br /><br />
FINAL_SCORE;
session_destroy();
}
else
{
$number++;
$_SESSION["number"] = $number;
$x = rand(1, 100);
$y = rand(1, 100);
$question = $x . " + " . $y . " = ";
$answer = $x + $y;
$_SESSION["question"] = $question;
$_SESSION["answer"] = $answer;
$script = $_SERVER['PHP_SELF'];
print <<<FORM
<form method = "post" action = $script>
$question
<input type = "text" name = "answer" value = "" size = "5" />
<input type = "submit" value = "Check Answer" />
</form>
FORM;
}

print <<<BOTTOM
</body>
</html>
BOTTOM;

?>

You might also like