Chap4 Cookies

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

I.

Cookies:
Cookie is a small piece of data that a server sends to the user's web browser. The
browser may store it and send it back with the next request to the same
server. Typically, it's used to tell if two requests came from the same browser —
keeping a user logged-in, for example. It remembers stateful information for
the stateless HTTP protocol.

Cookie is created at server side and saved to client browser. Each time when client
sends request to the server, cookie is embedded with request. Such way, cookie can
be received at the server side.

In short, cookie can be created, sent and received at server end. Each time the
browser requests a page to the server, all the data in the cookie is automatically
sent to the server within the request

There are two types of cookies:


1. Session Cookies
2. Permanent Cookies
By default, cookie has a lifetime of browser window. When a browser is closed,
the cookie is gone. It is deleted. Such a cookie is called as Session Cookie. You
can also create a Permanent Cookie by specifying an expiry:

Why to use Cookies?

Http is a stateless protocol; cookies allow us to track the state of the application
using small files stored on the user’s computer.

II. Where the cookies are stored in Browser?

The path where the cookies are stored depends on the browser.
Example-

1. Internet Explorer usually stores them in Temporal Internet Files folder.


2. Google Chrome: SettingsPrivacy and Security->Site Settings->Cookies
and Site Data->See all the cookies and site data

III. Restrictions of cookies


1. Cookies can only store 4KB of data
2. Cookies are private to the domain or cookies are domain specific. One
domain cannot read or write to the cookie created by another domain. This is
done by the browser for security purpose.
3. A site can only read the cookies it set, not other domains cookies
4. You can have up to 20 limits of cookies per domain (but the exact number
depends on the specific browser implementation). If the limit is exceeded,
the new cookies will replace the old cookies.
5. Cookies are browser specific. Each browser stores the cookies in a different
location. The cookies are browser specific and so a cookie stored in one
browser(e.g in Google Chrome) will not be accessed by another
browser(Internet Explorer/Firefox).

IV. Uses of Cookies:

Cookies are often used to perform following tasks:

1. Session management: Cookies are widely used to manage user sessions.


For example, when you use an online shopping cart, you keep adding
items in the cart and finally when you checkout, all of those items are
added to the list of items you have purchased. This can be achieved using
cookies.
2. User identification: Once a user visits a webpage, using cookies, that
user can be remembered. And later on, depending upon the search/visit
pattern of the user, content which the user likely to be visited are served.
A good example of this is 'Retargetting'. A concept used in online
marketing, where depending upon the user's choice of content,
advertisements of the relevant product, which the user may buy, are
served.
3. Tracking / Analytics: Cookies are used to track of the user. Which, in
turn, is used to analyze and serve various kind of data of great value, like
location, technologies (e.g. browser, OS) form where the user visited,
how long (s)he stayed on various pages etc.

V. Advantages of using cookies:

1.  Cookies are simple to use and implement, they do not need any server
resource.
2. Occupies less memory, do not require any server resources and are stored
on the user's computer so no extra burden on server.
3. We can configure cookies to expire when the browser session ends
(session cookies) or they can exist for a specified length of time on the
client’s computer (persistent cookies). Cookies persist a much longer
period of time than Session state.
4. The cookies are stored on the client’s hard disk , so , if server crashes
the cookies are still available .

VI. Disadvantages of using cookies:

1. Cookies are not secure as they are stored in clear text, they may pose a possible
security risk as anyone can open and tamper with cookies. You can manually
encrypt and decrypt cookies, but it requires extra coding and can affect
application performance because of the time that is required for encryption and
decryption
2. Several limitations exist on the size of the cookie text (4kb in general), number
of cookies (20 per site in general), etc.  
3.    User has the option of disabling cookies on his computer from browser’s
setting .
·         Cookies will not work if the security level is set to high in the browser.
·         Users can delete a cookies.
·         Users browser can refuse to use cookies
·         Complex type of data not allowed (e.g. dataset etc). It allows only plain
text (i.e. cookie allows only string content)

Creating the cookies:


1. Setcookie() – It sets or creates the cookie. It takes 6 arguments. It returns
Boolean value. To create each cookie, this function has to be called
separately.

Syntax: setcookie(Name, Value, [Expiry_Time], [Cookie_Path], [Domain],


[Secure]);

Where, First 3 arguments are mandatory to mention


1. Name: Name of Cookie
2. Value: Content of Cookie-Content can be integer or string.
3. Expiry: Expiry time of Cookie. After this time cookie will become
inaccessible. The default value is 0. If the expiration time of the cookie is set
to 0, or omitted, the cookie will expire at the end of the session i.e. when the
browser closes.
4. Path: Specify the path on the server for which the cookie will be available. If
set to /, the cookie will be available within the entire domain.
5. domain: It defines cookie access hierarchy. It is used to specify the domain
for which the cookie is available.
6. secure: optional, the default is false. It is used to determine whether the
cookie is sent via https if it is set to true or http if it is set to false.

Superglobal Variable $_COOKIE:

To access a cookie value, the PHP $_COOKIE superglobal variable is used.It is an


associative array that contains a record of all the cookies values sent by the
browser in the current request. The records are stored as a list where cookie name
is used as the key.

If you wish to retreive all the cookies, you may use the following command

<?php
print_r($_COOKIE);
?>
Programs using Cookies

1. Write a PHP script to create and view the content of cookie [Hint:
setcookie() and $_COOKIE]
Solution:
<?php
setcookie("sybca","PHP Demo of Cookie", time()+60);
echo $_COOKIE["sybca"];
?>
<html>
<head><title>Cookie Demo</title></head>
<body>
<h1> Hello Students</h1>
</body>
</html>

2. Write a script to keep track of number of times the web page has been
accessed [Hint: Use $_COOKIE].
Solution:
<?php
if(isset($_COOKIE['bca']))
{
$x=$_COOKIE['bca'];
$x=$x+1;
setcookie('bca',$x);
echo "you accessed this page $x times";
}
else
{
$x=1;
setcookie('mca',$x);
echo "you accessed this page for $x time";
}
?>
3. Create a form to accept employee details like name, address and mobile
number. Once the employee information is accepted, then accept LIC
information like policy_no, name, premium. Display employee details and
LIC details on next form.(use COOKIE)

Solution

Emp.html

<html>
<body>
<form action="/php programs/lic.php" method="post">
<center>
<h2>Enter Employee Details :</h2>
Name :<input type="text" name="nm"><br><br>
Address :<input type="text" name="addr"><br><br>
Mobile No : </td><td><input type="text" name="mno"><br><br>
<br><input type="submit" value="Next">
</center>
</form>
</body>
</html>

Lic.php

<html>
<body>
<form action="/php programs/emp-policy.php" method="post">
<center>
<h2>Enter LIC Information :</h2>
<br>Policy no. : </td><td><input type="text" name="pno">
<br>Policy Name : </td><td><input type="text" name="pnm">
<br>Premium : </td><td><input type="text" name="premium">
<br><input type="submit" value="Next">
</center>
</form>
</body>
</html>
<?php
setcookie("emp1",$_POST['nm'],time()+3600);
setcookie("emp2",$_POST['addr'],time()+3600);
setcookie("emp3",$_POST['mno'],time()+3600);
?>

Emp-policy.php

<?php
echo"<center>";
echo "<h3>Employee Details</h3> ";
echo "<b>Name : </b>".$_COOKIE['emp1']."<br>";
echo "<b>Address : </b>".$_COOKIE['emp2']."<br>";
echo "<b>Mobile No. : </b>".$_COOKIE['emp3']."<br>";
echo "<b>Policy no. : </b>".$_POST['pno']."<br>";
echo "<b>Policy Name : </b>".$_POST['pnm']."<br>";
echo "<b>Premium : </b>".$_POST['premium']."<br>";
echo"</center>";
?>

4. Change the preferences of your web page like font style, alignment, font size,
font color, background color using cookie. Display selected settings on next web
page and actual implementation (with new settings) on third web page.
Solution:

Settings.html
<html>
<body>
<form action="/php programs/format.php" method="get">
<center>
<b>Select font Alignment :</b><input type="text" name="t1"><br><br>
<b>Enter font size : </b><input type="text" name="t2"><br><br>
<b>Enter Font Color :</b><input type="text" name="t3"><br><br>
<b>Enter background color :</b> <input type="text" name="t4"><br><br>
<input type="submit" value="Next">
</center>
</form>
</body>
</html>
Format.php

<?php
echo "<br>Alignment is ".$_GET['t1'];
echo "<br>Background color is ".$_GET['t4'];
echo "<br>Font Color is",$_GET['t3'];
echo" <br>size is ".$_GET['t2'];
setcookie("set1",$_GET['t1'],time()+3600);
setcookie("set2",$_GET['t2'],time()+3600);
setcookie("set3",$_GET['t3'],time()+3600);
setcookie("set4",$_GET['t4'],time()+3600);
?>
<html>
<body>
<form action="/php programs/implementation.php">
<input type=submit value="OK">
</form>
</body>
</html>

Implementation.php

<?php
$style=$_COOKIE['set1'];
$size=$_COOKIE['set2'];
$color=$_COOKIE['set3'];
$bcolor=$_COOKIE['set4'];
$msg="Hello Students";
echo "<body style='text-align:$style;color:$color;background-color:$bcolor;size:
$size'>$msg</body>";
?>
5. Create a form to accept student information (name, class, address).
Once the student information is accepted, accept marks in next form
(Java, PHP, ST, IT, pract1, and project). Display the mark sheet for
the student in the next form containing name, class, marks of the
subject, total and percentage(Use $_COOKIE).

Solution:

Stud.html

<html>
<body>
<form action="/php programs/marks.php" method="post">
<center>
<h2>Enter Students information :</h2>
<br>Name : </td><td><input type="text" name="name"></br></br>
<br>Address : </td><td><input type="text" name="addr"></br></br>
<br>Class :<input type="text" name="class"></br></br>
<input type="submit" value=Next></br></br>
</center>
</form>
</body>
</html>

Marks.php

<html>
<body>
<form action="/php programs/marksheet.php" method="post">
<center>
<h2>Enter Marks for Student:</h2>
<br>Java : <input type="text" name="m1"><br>
<br>PHP : <input type="text" name="m2"></br>
<br>ST : <input type="text" name="m3"><br>
<br>IT : <input type="text" name="m4"></br>
<br>Practical : <input type="text" name="m5"></br>
<br>Project : <input type="text" name="m6"></br></br>
<br><input type="submit" value=Next></br></br>
</center>
</form>
</body>
</html>
<?php
setcookie("stud1",$_POST['name'],time()+3600);
setcookie("stud2",$_POST['addr'],time()+3600);
setcookie("stud3",$_POST['class'],time()+3600);
?>

Marksheet.php

<?php
echo "<h3>Marksheet</h3> ";
echo "<br>Name : ".$_COOKIE['stud1'];
echo "<br>Address : ".$_COOKIE['stud2'];
echo "<br>Class : ".$_COOKIE['stud3'];
echo "<br>Java : ".$_POST['m1'];
echo "<br>PHP : ".$_POST['m2'];
echo "<br>ST : ".$_POST['m3'];
echo "<br>IT : ".$_POST['m4'];
echo "<br>Practical : ".$_POST['m5'];
echo "<br>Project : ".$_POST['m6'];
?>

4. Create student registration form and display details in the next page. [use
cookies]

Registration .php
<html>
<body>
<form action="/php programs/show.php" method=post>
<br>Enter Name<input type="text" name="nm" >
<br>Enter Roll No<input type="text" name="rno" >
<brEnter State<input type="text" name="st" >
<br>Enter City<input type="text" name="ct">
<br>Enter Percentage<input type="text" name="per" >
<br><input type="submit" value="Submit" name="submit"></form>
</html>
<?php
if(isset($_POST['submit']))
{
$nm=$_POST['nm'];
$rno=$_POST['rno'];
$st=$_POST['st'];
$ct=$_POST['ct'];
$perc=$_POST['per'];
}
if((!empty($nm)) && (!empty($rno)) && (!empty($st)) && (!empty($ct)) && (!
empty($perc)))
{
setcookie('nm',$nm);
setcookie('rno',$rno);
setcookie('st',$st);
setcookie('ct',$ct);
setcookie('perc',$perc);

}
?>
</body>
</html>

show.php
<?php
echo "<br>Your name is $_COOKIE[nm] ";
echo "<br>Your Roll No Is : $_COOKIE[rno]";
echo "<br>Your State Is : $_COOKIE[st]";
echo "<br>Your City Is : $_COOKIE[ct]";
echo "<br>Your Percentage Is : $_COOKIE[perc]";

?>

You might also like