You are on page 1of 35

Chapter 9

Chapter 9 PHP Cookies, Sessions &


Authentication
What is Cookie?
• A cookie is a small file that the web server stores on the
client computer to be used only by the website setting the
cookies.
• Once a cookie has been set, all page requests that follow
return the cookie name and value.
• It is often used to identify a user.
• A cookie created by a user can only be visible to him. Other
users cannot see its value.

2
Why and when to use Cookies?
• Http is a stateless protocol; in other word the server will
forget everything related to client/browser state.
• Personalizing the user experience – this is achieved by
allowing users to select their preferences.
• Tracking the pages visited by a user.

3
Advantages of cookies
• User Friendly
Cookies are extremely user friendly. The client can choose
what they need to do with cookies.
Availability
Cookies can also set to be made available for a longer time.
• Convenience
Besides websites, cookies can also remember information
related to forms. However, cookies will not remember
confidential information such as credit card info.

4
Advantages of cookies (cont…)
• Marketing
Most companies, especially, e-commerce sites tends to use
cookies to target products to their customers.
• Configurations
Cookies can also be configured as per the requirement. For an
example, it can be made to expire once the user closes the
browser tab or set to exist only for a specific time.

5
Advantages of cookies (cont…)
• Server Requirement
All the data related to cookies are stored on the client’s hard
drive without the use of server resources. No extra load or
weight is added to the server.

6
Disadvantages of using cookies
• Browser Impacts
Cookies are not restricted based on internet usage.
• Security Risks
Since cookies are stored in the hard drive as text files, it posses
some serious security risks. Any intruder can easily open these
files and view the information.
• Size Limitations
• Size limitations also exist on cookies (4kb in general). Browsers
too pose restrictions when it comes to number of cookies (20
per site in general for single web site).
7
Disadvantages of using cookies (cont…)
• Privacy Concerns
Apart from security, privacy is another concern for users in
cookies. Whenever the user browses the internet, the cookie
enabled sites will be recording all the online activities.
• Manual Disabling
Browsers also comes with the option to disable cookies.
Encoding Information
Both encrypting and decrypting cookies is a difficult process
since it requires additional coding.

8
Creating Cookies
• A cookie is created with the setcookie ( ) function.
• Syntax:
<?php
setcookie (cookie_name, cookie_value, [expiry_time],
[cookie_path], [domain], [secure], [httponly]);
?>

9
setcookie ( ) Function Parameters
Only the name and value parameters are required. All other
parameters are optional. Were,
• “setcookie” is the PHP function used to create the cookie.
• “cookie_name” is the name of the cookie that the server will
use when retrieving its value from the $_COOKIE array
variable.
• “cookie_value” is the value of the cookie.

10
setcookie ( ) Parameters (cont…)
• “[expiry_time]” is optional; it can be used to set the expiry
time for the cookie. The time is set using the PHP time ( )
function plus number of seconds greater than 0. Default is 0
which mean that the cookie will expire at the end of the
session (when the browser closes).
• “[cookie_path]” is optional; it can be used to set the cookie
path on the server. The forward slash “/” means that the
cookie will be made available on the entire domain.

11
setcookie ( ) Parameters (cont…)
• “[domain]” is optional, it can be used to define the cookie
access hierarchy.
• “[secure]” is optional, 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.
• “[Httponly]” is optional, default is false. If it is set to true,
then only client-side scripting languages i.e. JavaScript can
access them.

12
Notice
• The php setcookie( ) function must appear before the HTML
opening tag.

13
Exmple
<?php
$cookie_name = "user";
$cookie_value = "Abdullahi Mohamed Abdi";
$cookie_time = 60;
setcookie($cookie_name, $cookie_value, time() + $cookie_
time);
?>

14
Retrieving the Cookie value
• You can retrieve cookie’s values using PHP built-
in super global variable $_COOKIE (passed
cookie name as index). It contains the name and
value of the cookie.
• We also use the isset ( ) function to find out if
the cookie is set.

15
Example
if(!isset($_COOKIE[$cookie_name]))
echo("<br>Cookie named <b>$cookie_name </b> is not
set");
else {
echo("<br>The cookie '$cookie_name' has been set for
$cookie_time seconds");
echo("<br>Value is: " . $_COOKIE[$cookie_name]);
}

16
Delete Cookies
• If you want to destroy a cookie before its expiry time, then
you set the expiry time to a time that has already passed.
• Example:
setcookie ($cookie_name, $cookie_value, time ( ) - 60);

17
Check if Cookies are Enabled
• Create a cookie then count the $_COOKIE array variable.
• For example,
<?php
if(count($_COOKIE) > 0)
echo "Cookies are enabled.";
else
echo "Cookies are disabled.";
?>

18
What is a Session?
• A session is a way to store information (in global variables)
on the server to be used across multiple pages.
• Each session is assigned a unique name which is used to
retrieve stored values.
• 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.

19
What is a Session? (cont…)
• Session variables hold information about one single user and
are available to all pages in one application.

20
Advantages of Sessions
• Limit the number of logins
Application can allow limit logins at a time. If the limit is
exceeded, then further users may not be allowed to log in.
• Block multiple logins for same username
Application can make a user login from only 1 location at a
time for security purpose. The sessions table can simply delete
the earlier session data of a particular username and login the
new one.

21
Advantages of Sessions (cont…)
• Monitor user activity
View which user is currently online, when did he login, what he did,
and for how long has he been active.
• Logout a user

A user can be logged out simply by removing his session entry in the
database. This can be useful to logout users who have been inactive
for a long time.
• It is very easy to implement.

• One big advantage of session is that we can store any kind of data type
in it.
22
Disadvantages of Sessions
• Performance overhead in case of large volumes of
data/user, because session data is stored in the
server’s memory.

23
Retrieving Session Variables
• 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.
• You can use sessions when developing an application such as
a shopping cart that has to temporary store information with
a capacity larger than 4KB.

24
Creating a Session
• In order to create a session, you must first call the PHP
session_start ( ) function and then store your values in the
$_SESSION array variable.
• We use the isset ( ) function to find out if the session is set.
• Next slide example demonstrates how to retrieve values
from sessions and displays number of times that a page has
been loaded.

25
Example
<?php
session_start ( );
if(isset($_SESSION['page_count']))
$_SESSION['page_count'] += 1;
else
$_SESSION['page_count'] = 1;
echo ("You are visitor number: " . $_SESSION['page_count']);
?>

26
Destroying Session Variables
• The session_destroy ( ) function is used to destroy the whole
PHP session variables. If you want to destroy only a single
session, you use the unset ( ) function.
• Example:
<?php
session_destroy ( ); //destroy all session variables
unset ($_SESSION['page_count']); //destroy only
page_count session variable
?>
27
Notice
• session_destroy ( ) function removes all the session data
including cookies associated with the session. Unset function
only frees the individual session variables. Other data
remains intact.

28
Chapter Summary
• Cookies are small files saved on the user’s computer.
• Cookies can only be read from the issuing domain.
• Cookies can have an expiry time, if it is not set, then the
cookie expires when the browser is closed.
• Sessions are like global variables stored on the server.
• Each session is given a unique identification that is used to
track the variables for a user.
• Both cookies and sessions must be started before any HTML
tags have been sent to the browser.
29
Practical examples
• In the following examples, we will design and program user
registration form and login form.
• First, design the database for user table that contains almost
columns: user id, first name, middle name, last name, sex,
username, password, recovery question, answer, user type,
status, user profile photo, registration date, and who
registered.
• We will use this table for user registration and login

30
User registration form
• Contains the following controls:
• User id, first name, middle name,
last name, sex, username,
password, confirmation, recovery
question, answer, user type,
status, user profile picture, and
submit button.

31
User registration form
• Guide to create a user registration form in PHP
⮚Step 1- Create an HTML user registration form that
contains controls mentioned in the previous slides.
⮚Step 2: Create a CSS Code to style the registration form.
⮚Step 3: Open a connection to a MySQL database and
create PHP code for registration page.
⮚Step 4: Code for all necessary validations.

32
Login form
• Contains username,
password, remember me
checkbox, forgot password,
sign up, and submit button.

33
Practical example: Login form
• Guide to create a login form in PHP
⮚Step 1- Create a HTML Login Form that contains username,
password, remember me checkbox, forgot password, sign-up, and
submit button
⮚Step 2: Create a CSS Code to style the Login form page.
⮚Step 3: Open a connection to a MySQL database and create PHP
code for login page.
⮚Step 4: Create code for remember me, forgot password using
cookie and session.
⮚Step 5: Create PHP code for Control panel page to login into it
⮚Step 6: Create a Logout page.
⮚Step 7: Code for all necessary validations.
34
`

END
35

You might also like