0% found this document useful (0 votes)
4 views27 pages

Web System Chapter v6.0

Chapter Six discusses the importance of cookies and sessions in web applications for maintaining state in the inherently stateless HTTP protocol. It explains how cookies store data on the client-side while sessions store data on the server-side, highlighting their respective use cases and security implications. The chapter also covers implementation details in PHP, including cookie creation, usage, and session management.

Uploaded by

BIRUK GEBRE
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)
4 views27 pages

Web System Chapter v6.0

Chapter Six discusses the importance of cookies and sessions in web applications for maintaining state in the inherently stateless HTTP protocol. It explains how cookies store data on the client-side while sessions store data on the server-side, highlighting their respective use cases and security implications. The chapter also covers implementation details in PHP, including cookie creation, usage, and session management.

Uploaded by

BIRUK GEBRE
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/ 27

Web Systems and

Services

CHAPTER SIX
COOKIES AND SESSIONS IN WEB
APPLICATIONS

BITS College
Addis Ababa, Ethiopia, 2025

Lecturer Name:

6/13/2025 1
6/13/2025 2
6/13/2025 3
The Need for Persistence

HTTP is Stateless
HTTP does not remember previous requests; web
applications need to track page visits, store form data, and
maintain user logins.

Persistence Definition
Persistence keeps data even after the program ends; the
simplest method is saving to a file. Therefore, persistence
is important for web applications.

6/13/2025 4
Persistence Mechanisms in PHP

Cookies (Client-Side) Sessions (Server-Side)

Cookies store information Sessions store information


on the user's computer. on the server and link it to a
unique user ID.

HTTP
Client server

Session
Cookie

6/13/2025 5
What are HTTP Cookies?

Cookie Definition
A cookie is a packet of information sent from the
server to the client and back on each access.

State Introduction
Cookies introduce state into HTTP, which is
inherently stateless, enabling personalized user
experiences.

6/13/2025 6
How Cookies Work

Cookie Transfer Cookie Analogy

Cookies are transferred between the server and client via Cookies can be thought of as tickets used to identify clients
HTTP headers. and their orders, maintaining continuity.

6/13/2025 7
Implementing Cookies

Sending Cookies

The server sends cookies to the client via "Set-Cookie"


headers.

Header Attributes

`Set-Cookie: NAME=VALUE; expires=DATE; path=PATH;


domain=DOMAIN_NAME; secure`;
NAME is a URL-encoded name,
PATH and DOMAIN specify cookie applicability.

6/13/2025 8
setcookie(name,value,expire,path,domain,secure)
Parameter Description
name (Required). Specifies the name of the cookie
value (Required). Specifies the value of the cookie
expire (Optional). Specifies when the cookie expires.
e.g. time()+3600*24*30 will set the cookie to expire in 30 days.
If this parameter is not set, the cookie will expire at the end of the session (when
the browser closes).
path (Optional). Specifies the server path of the cookie.

If set to "/", the cookie will be available within the entire domain.
If set to "/phptest/", the cookie will only be available within the test directory and
all sub-directories of phptest.

The default value is the current directory that the cookie is being set in.
domain (Optional). Specifies the domain name of the cookie.
To make the cookie available on all subdomains of example.com then you'd set it
to ".example.com".
Setting it to www.example.com will make the cookie only available in the www
subdomain
secure (Optional). Specifies whether or not the cookie should only be transmitted over a
secure HTTPS connection.
TRUE indicates that the cookie will only be set if a secure connection exists.
6/13/2025 Default is FALSE. 9
Cookies from HTTP

Client (e.g. Firefox) it026945

GET /*.html HTTP/1.1


Host: it026954.domain
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie:
name=value
GET /*.html HTTP/1.1
(content of page)
Host: it026945.domain
Cookie: name=value
Accept: */*

6/13/2025 10
PHP Cookies: Creation and Usage
Creating Cookies with `header()`

Direct Manipulation
Cookies can be set by directly manipulating
HTTP headers using the PHP `header()`
function.

Example
`<?php header(“Set-Cookie:
mycookie=myvalue; path=/;
domain=.coggeshall.org”); ?>` sets a cookie
named "mycookie".

6/13/2025 11
PHP Cookies: Creation and Usage

UsageCreating Cookies with `setcookie()`

Function Parameters Example

`Setcookie (name,value,expire, path, domain, secure)`;


Name is the cookie's name, Value is the stored data,
Expire is the lifetime, Path is valid URLs, Domain is the
domain, Secure for HTTPS.

6/13/2025 12
PHP Cookies: Creation and Usage

Reading Cookies

Superglobal Array Accessing Values

To access a cookie, use the Each key in the array


PHP `$_COOKIE` represents a cookie; the key
superglobal array. name is the cookie name,
and the value is the
cookie’s content.

6/13/2025 13
Cookie Visibility

Page Load
Cookies only become visible on the next page
load; they are not immediately available.

Refresh
After setting a cookie, refresh the page to view
the cookie's effect.

6/13/2025 14
Cookie Visibility

Page Load
Cookies only become visible on the next page
load; they are not immediately available.

Refresh
After setting a cookie, refresh the page to view
the cookie's effect.

6/13/2025 15
Correct Header Usage

Header Ordering
Cookies must be sent before any
other heading elements.

Ensuring Success
Using headers `setcookie()` must run
before any information is sent to the
browser to avoid errors.

6/13/2025 16
Multiple Data Items
Code Example
Using `explode()` <?php
$strAddress = $_SERVER['REMOTE_ADDR'];
$strBrowser = $_SERVER['HTTP_USER_AGENT'];
$strOperatingSystem = $_ENV['OS'];
$strInfo =
"$strAddress::$strBrowser::$strOperatingSyst
em";
setcookie ("somecookie4",$strInfo, time()+7200);
?>
<?php
$strReadCookie = $_COOKIE["somecookie4"];
$arrListOfStrings = explode ("::",
$strReadCookie);
Use `explode()` to store multiple data items in a single echo "<p>$strInfo</p>";
cookie. echo "<p>Your IP address is: $arrListOfStrings[0]
</p>";
echo "<p>Client Browser is: $arrListOfStrings[1]
</p>";
echo "<p>Your OS is: $arrListOfStrings[2] </p>";
6/13/2025 ?> 17
Deleting a Cookie

Simple Deletion

Set the cookie with its name only to delete it.

Example

`setcookie(“mycookie”);` will delete the 'mycookie'


after the page reloads

6/13/2025 18
What are PHP Sessions?

User Information
Store user information (e.g., username,
items selected) on the server-side for
later use using PHP sessions.

Unique ID
Sessions work by creating a unique ID
(UID) for each visitor and storing
variables based on this UID.

6/13/2025 19
Usage Scenarios

Server-Side Data

Use sessions when you need data stored on the


server.

Transient and Secure


Data

For unique session information, transient data, or


data that should not be exposed, use sessions.

6/13/2025 20
Sessions vs. Cookies

Storage Location
Cookies are stored on the client-side, while
sessions are stored on the server-side.

Security
Sessions are more secure; once established,
no data is sent back and forth between the
machines.

6/13/2025 21
Managing Sessions

Starting a Session

`session_start()` Session ID
Function
`<?php session_start(); ?>` A session ID is allocated at
function must appear the server end; it looks
BEFORE the `<html>` tag. like
`sess_f1234781237468123
768asjkhfa7891234g`.

6/13/2025 22
Managing Sessions
Session Variables
 With session_start() a default session variable is
created - the name extracted from the page name
`$_SESSION` Superglobal  To create your own session variable just add a new
key to the $_SESSION superglobal

Use `$_SESSION` to create session variables, e.g., $_SESSION[‘dug’] = “a talking dog.”;


`$_SESSION[“intVar”] = 10;`.

Testing Variables

`session_start(); if(!$_SESSION['intVar']) {…}` checks if


`intVar` is set.

6/13/2025 23
Managing Sessions
Ending Sessions

Unsetting Variables

`unset($_SESSION[‘name’])` removes a
session variable.

Destroying Sessions

`session_destroy()` destroys all data


registered to a session, but not global
variables and cookies.

6/13/2025 24
Complete Destruction Code

Code Example
session_start();
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() -
42000,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]
);
}
session_destroy();
?>

6/13/2025 25
Key Takeaways

Cookies and Sessions are


important tools in web
development
Cookies and sessions are essential for
creating persistent and dynamic web
applications, each with its advantages and
use cases.
Consider Security
Implications
Always be aware of security implications
and choose the right method for storing
data.

6/13/2025 26
Thank You !!!

6/13/2025 27

You might also like