0% found this document useful (0 votes)
37 views23 pages

Beisa Document

The document discusses cookies and sessions in PHP. It defines what cookies and sessions are, how to create, access, and destroy them in PHP. It also explains how cookies and sessions can be used for features like login and shopping carts.

Uploaded by

bayisadamisse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views23 pages

Beisa Document

The document discusses cookies and sessions in PHP. It defines what cookies and sessions are, how to create, access, and destroy them in PHP. It also explains how cookies and sessions can be used for features like login and shopping carts.

Uploaded by

bayisadamisse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

MIZEN TEPI UNIVERSITY

SCHOOL OF COMPUTING AND INFORMATICS

DEPARTMENT OF SOFTWARE ENGINEERING

Individual Assignment Cookies and Sessions

Prepare By

Student Name ID
Beyisa Demise 0721/14

Submi ed to Mr MELKAMU

Submission date 01/9/2016


Individual Assignment of Web design and Programming
Individual Assignment of Web design and Programming

Table of Contents……………………………………………………………………………..page
1 Introduc on ............................................................................................................................................... ii
2 What is Cookie? ......................................................................................................................................... 1
2.1 Create Cookies in PHP ......................................................................................................................... 3
2.3 Checking Whether a Cookie Is Set Or Not: ......................................................................................... 5
2.3 Accessing cookie ................................................................................................................................. 6
2.5 Removing Cookies ............................................................................................................................... 7
2.6 Scope of cookies.................................................................................................................................. 8
2.7 Cookies and their use .......................................................................................................................... 9
2.7.1 Shopping cart ............................................................................................................................... 9
2.7.2 Login ............................................................................................................................................. 9
2.8 Cri cism of cookies ............................................................................................................................. 9
3 What is a Session?...................................................................................................................................... 9
3.1 Star ng PHP session .......................................................................................................................... 10
3.2 How to Access Values From a Session in PHP? ................................................................................. 11
Example .............................................................................................................................................. 12
3.3 How to register a variable in PHP session ? .......................................................................................... 12
3.4 Storing and Accessing Session Data ................................................................................................. 16
3.5 Destroying PHP session ..................................................................................................................... 17
3.5.1 How to Destroy a Session in PHP? .............................................................................................. 17
Session for login .......................................................................................................................................... 17
4 Conclusion ............................................................................................................................................... 18
5 Reference ................................................................................................................................................. 19

i|Page
Individual Assignment of Web design and Programming

1 Introduction

 HTTP is a stateless protocol.


 A stateless protocol does not require the server to retain information or status about each user
for the duration of multiple requests.
 This means that after an exchange is over...
 a browser requests a resource from a server
 the web server sends the resource to the browser
 the connection will be closed and forgotten
 Each request back to the server will include these pieces of data.
 The data is organized as key/value pairs.
 they consist of two HTTP header

ii | P a g e
Individual Assignment of Web design and Programming

2 What is Cookie?

 A cookie is a small file with the maximum size of 4KB that the web server stores on the
client computer.
 Once a cookie has been set, all page requests that follow return the cookie name and
value.
 A cookie can only be read from the domain that it has been issued from.
 Most of the websites on the internet display elements from other domains such as
advertising. The domains serving these elements can also set their own cookies.
 These are known as third party cookies.
 A cookie created by a user can only be visible to them.
 Other users cannot see its value.
 Most web browsers have options for disabling cookies, third party cookies or both.
 If this is the case then PHP responds by passing the cookie token in the URL

 Cookies may be limited in time with an expiration date


 else the cookie will be deleted when the browser is closed
 Cookies, or browser cookies, are small pieces of data which the web server asks the
client's web browser to store.
 Each request back to the server will include these pieces of data.
 The data is organized as key/value pairs.
 they consist of two HTTP headers:
 When a client sends a request for a particular URL, the server can opt to include a Set-
Cookie header in the response, so as to request for the client to include a corresponding
Cookie header in its future request.
 A cookie can be set using PHP's setcookie() function.

Syntax
setcookie(string name, string value, int expire, string path,
string domain, int secure);

1
Individual Assignment of Web design and Programming

<?php
setcookie('language', 'english');
?>

On future requests, the cookie key/value pairs will assigned to the $_COOKIE superglobal.

<?php
echo $_COOKIE['language'];
// english
?>

 In addition to the $name and $value arguments, setcookie() also accepts many other
arguments for configuration.

<?php
$name = 'language';
$value = 'english';
$expire = time() + 60*60*24*3; // 3 days from now
$path = '/blog';
$domain = 'www.mysite.com';
$secure = isset($_SERVER['HTTPS']); // or use true/false
$httponly = true;

setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);


?>

Many of these configuration arguments are important for preventing attacks such as Cross-Site
Scripting (XSS), Cross-Site Request Forgery (CSRF), Cookie Theft and Manipulation, Session
Hijacking, and Session Fixation.

2
Individual Assignment of Web design and Programming

The diagram shown below illustrates how cookies work

Here,
 1) A user requests for a page that stores cookies
 2) The server sets the cookie on the user’s computer
 3) Other page requests from the user will return the cookie name and value Cookies

2.1 Create Cookies in PHP


A cookie can be set using PHP's setcookie() function.
Syntax setcookie(string name, string value, int expire, string path,
string domain, int secure);
Example 1
<?php
// Setting a cookie
setcookie("username", “Abebe", time()+10*24*60*60);
?>

3
Individual Assignment of Web design and Programming

 Below are some operations that can be performed on Cookies in PHP:


 Creating Cookies: Creating a cookie named Auction_Item and assigning the value Luxury
Car to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.

<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."

4
Individual Assignment of Web design and Programming

?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
</body>
</html>

2.3 Checking Whether a Cookie Is Set Or Not:

It is always advisable to check whether a cookie is set or not before accessing its
value. Therefore to check whether a cookie is set or not, the PHP isset() function is
used. To check whether a cookie “Auction_Item” is set or not, the isset() function is
executed as follows:
Example: This example describes checking whether the cookie is set or not
<!DOCTYPE html>

<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

if (isset($_COOKIE["Auction_Item"]))

echo "Auction Item is a " . $_COOKIE["Auction_Item"];

else

5
Individual Assignment of Web design and Programming

echo "No items for auction."; }

?>

<p>

<strong>Note:</strong>

You might have to reload the page

to see the value of the cookie.

</p>

</body>

</html>

2.3 Accessing cookie

The PHP $_COOKIE super global variable is used to retrieve a cookie value.

For accessing 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 the cookie name is used as the key. To

access a cookie named “Auction_Item”, the following code can be executed

Example 1
<html>
<head><title>sample on cookie</title></head>
<body>
<?php
if(!isset($_COOKIE["username"]))
{
setcookie("username", "Abebe", time()+10*24*60*60);
}
else{
echo $_COOKIE["username"]; // used to access a cookie
}?>
</body>
</html>

6
Individual Assignment of Web design and Programming

Example 2: This example describes accessing & modifying the cookie value.

<!DOCTYPE html>

<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

echo "Auction Item is a " . $_COOKIE["Auction_Item"];

?>

<p>

<strong>Note:</strong>

You might have to reload the page

to see the value of the cookie.

</p>

</body>

</html>

2.5 Removing Cookies

The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie()
function is called by passing the cookie name and other arguments or empty strings but
however this time, the expiration date is required to be set in the past. To delete a cookie
named “Auction Item”, the following code can be executed.

Cookies can be deleted by calling the setcookie() function with the cookie name and any value
(such as an empty string) with expiration date set in the past,

Example 1

7
Individual Assignment of Web design and Programming
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>
Example 2

<!DOCTYPE html>

<?php

setcookie("Auc on_Item", "Luxury Car", me() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

setcookie("Auc on_Item", "", me() - 60);

?>

<?php

echo "cookie is deleted"

?>

<p>

<strong>Note:</strong>

You might have to reload the page

to see the value of the cookie.

</p>

</body>

</html>

2.6 Scope of cookies

 Cookies can only be read from the site from which they were set
 This helps to ensure that one can not steal cookies (and thus iden es) through hos le
websites

8
Individual Assignment of Web design and Programming

2.7 Cookies and their use

2.7.1 Shopping cart


 when the front page appears, set a new (empty) cookie
 items are added by updating the cookie
 alternatively, one can store goods in the server’s database and just store an ID in the cookie
that points to your basket

2.7.2 Login
o user inputs name and password into a form

o after the combination has been verified, it sends a cookie to the user that identifies the user to the
system

o next time the user visits the page, the web server checks if there is a cookie, and if so the user is
identified

2.8 Criticism of cookies

 One can be completely anonymous on the net


 Most ads/banners come from relatively few advertisers.
 These may, with the help of cookies, follow a browser/ computer combination on all the
sites they advertise on.
 there have been examples of security vulnerabilities in browsers, so that adversaries can get
access to cookies
 which they can use to gain access to sites with a faked identity

3 What is a Session?

 A session is a global variable stored on the server.


 Each session is assigned a unique id which is used to retrieve stored values.
 Whenever a session is created, a cookie containing the unique session id is stored on the
user’s computer and returned with every request to the server. If the client browser does
not support cookies, the unique php session id is displayed in the URL

9
Individual Assignment of Web design and Programming

 Sessions have the capacity to store relatively large data compared to cookies.
 The session values are automatically deleted when the browser is closed. If you want to
store the values permanently, then you should store them in the database.
 Just like the $_COOKIE array variable, session variables are stored in the $_SESSION
array variable. Just like cookies, the session must be started before any HTML tags.
 A combination of cookies and data stored on the server (automatically by PHP)
 Saves a cookie containing an ID on the user’s computer that points to a session on the
server
 A session is a global PHP array ($_SESSION)
 A session is designed as an easy way to store data – for a short period
 a session’s lifetime in PHP is only 24 minutes by default

3.1 Starting PHP session

Sessions must be started at the top of the page before it is used.

Session start()

Session start() function creates a new session and generate a unique session ID for the user. it first
checks for an exis ng session ID. If it finds one, i.e. if the session is already started, it sets up the session
variables and if doesn't, it starts a new session by crea ng a new session ID

Example: How to Start a Session in PHP?

In the example below, you will start a session that will count how many times you have visited a
website page. For this, you will create a session variable named counter.

<?php

session_start();

if( isset( $_SESSION['counter'] ) ) {

$_SESSION['counter'] += 1;

}else {

10
Individual Assignment of Web design and Programming

$_SESSION['counter'] = 1;

$my_Msg = "This page is visited ". $_SESSION['counter'];

$my_Msg .= " time during this session.";

?>

<html>

<head>

<title>Starting a PHP session</title>

</head>

<body>

<?php echo ( $my_Msg ); ?>

</body>

</html>

3.2 How to Access Values From a Session in PHP?

You can access a session variable’s value by using the global variable $_SESSION. In the
example stated below, you will create another session with a variable that stores your name.

<?php

session_start();

?> <html>

<body>

11
Individual Assignment of Web design and Programming

<?php

$_SESSION["name"] = "Simplilearn";

echo "Information set in a variable.<br/>";

?>

</body>

</html>

Example

The following example starts a session then registers a variable called counter that is
incremented each time the page is visited during the session.

Use the isset() function to check if a session variable is already set or not.

The following PHP script starts a session when it runs for the first time, and sets a session
variable named counter. When the client revisits the same URL again, since the session variable
is already set, the counter is incremented.

3.3 How to register a variable in PHP session ?

The PHP session is required so that you can store the user information and use it on different
pages of the browser.
Approach: It creates a session with the name or any other useful information you want to store
and access on different pages. Even after your page is closed you can access the information
until the browser does not close. This is an important thing to understand if a browser is closed
then the session is automatically destroyed.
We can create the session by writing session start() and destroy the session by
using session_destroy(). You can access the session variable by writing $_session[“name”].
Example 1: In the following, you can create the session by entering the name. You can check
the working of the session by opening a new page in the same browser and retrieving the

12
Individual Assignment of Web design and Programming

session name. It gives you the name and this is how the session works and help us to store the
information

<?php

session_start();

?>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content=

"width=device-width, initial-scale=1">

<link rel="stylesheet" href=

"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<script src=

"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">

</script>

<script src=

"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js">

13
Individual Assignment of Web design and Programming

</script>

</head>

<body>

<div class="container">

<h2 style="color:green">GeeksforGeeks</h2>

<strong>Session Manager</strong></br>

<form method="POST">

<br/>Enter Name: <input type="text" name="name"> <br />

<br/>

<div>

<input type="submit" name="Submit1"

value="Create Session"

style="width:120;">

</div><br/>

<div>

<input type="submit" name="Submit2"

14
Individual Assignment of Web design and Programming

value="Retrieve Session"

style="width:120;">

</div>

<div><br/>

<input type="submit" name="Submit3"

value="Destroy Session"

style="width:120;">

</div>

</form>

</div>

<?php

// Creating a session with name

if(isset($_POST['Submit1']))

$_SESSION["sname"]=$_POST["name"];

echo "Session is created !!";

// Retrieve session by printing the session value

if(isset($_POST['Submit2']))

15
Individual Assignment of Web design and Programming

if(isset($_SESSION["sname"]))

echo "The Session Value = " . $_SESSION["sname"];

else

// If retrieve button is pressed and

// there is no session created

// then this message will be printed

echo "All Sessions Destroyed !!";

}}

if(isset($_POST['Submit3']))

{ session_destroy(); }

?>

</body>

</html>

3.4 Storing and Accessing Session Data

 session data can be stored as key-value pairs in the $_SESSION[] super global array.
16
Individual Assignment of Web design and Programming

 The stored data can be accessed during lifetime of a session.

<?php
// Starting session
Session start();
// Storing session data
$_SESSION["firstname"] = “Abebe";
$_SESSION["lastname"] = “Lemlem";
?>

3.5 Destroying PHP session

 all global session variables can be removed by destroing the session using:
 session unset(“session Id”) //remove all session variables

3.5.1 How to Destroy a Session in PHP?


Although the web server will terminate the session by default upon closing the browser, you can
also destroy it manually. Two functions can help you achieve this.

 Session destroy(): Calling this function will eliminate all the session variables

unset(): Calling this function will kill only the specified session variable

You can also use the session unset() function to remove all the variables of a session.

Let’s look at how to destroy the counter variable that you have created in one of the sessions
above.

 session destroy():// destroy the session


<?php
session_start();
// Removing session data <?php
if(isset($_SESSION[“username"])){ session_start();
session_unset($_SESSION[“username"]); // Destroying session
} session_destroy();
?>Session for login ?>

17
Individual Assignment of Web design and Programming

4 Conclusion

In this topic I am tray to define what is cookie? as flows

So cookie is a small file with the maximum size of 4KB that the web server stores on the client
computer and Cookies, or browser cookies, are small pieces of data which the web server asks
the client's web browser to store

I tray give some explain on what relation between or how the client use the cookies through this :
When a client sends a request for a particular URL, the server can opt to include a Set-Cookie
header in the response, so as to request for the client to include a corresponding Cookie header in
its future request.

For creating create the cookies I used and define the syntax so syntax form is represent as
Syntax setcookie(string name, string value, int expire, string path,
string domain, int secure);
other definition gave in this topic was what is session.? So a session is created, a cookie
containing the unique session id is stored on and A session is a global variable stored on the
server. Each session is assigned a unique id which is used to retrieve stored values ect.

18
Individual Assignment of Web design and Programming

5 Reference

https://www.tutorialspoint.com/php/php_cookies.htm
https://www.w3schools.com/php/func_network_setcookie.asp

https://www.geeksforgeeks.org/php-cookies/

https://wpwebinfotech.com/blog/how-to-use-cookies-in-php/

19

You might also like