UNIT IV: Sessions and cookies
SESSIONS in PHP
Definition
• A session is a way to store information (in variables) to be used across
multiple pages.
• A session create an alternative way to make data accessible across the
various pages of an entire website is to use a PHP Session.
• A session is a file in a temporary directory on the server where
registered session variables and their values are stored.
What is PHP session?
• When you work with an application, you open it, do
some changes, and then you close it. This is much like
a session. The computer knows who you are. It knows
when you start the application and when you end.
• But on the internet there is one problem: the web
server does not know who you are or what you do,
because the HTTP address doesn't maintain state.
PHP Session
• Session variables solve this problem by storing user
information to be used across multiple pages (e.g.
username, favourite color, etc). By default, session
variables last until the user closes the browser.
• Session variables hold information about one single
user, and are available to all pages in one application.
Session Technique
• PHP session technique is widely used in shopping websites where we
need to store and pass cart information e.g. username, product code,
product name, product price etc from one page to another.
Start a PHP Session
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.
• It starts a new or resumes existing session. It returns existing session
if session is created already.
• If session is not available , it creates and returns new session.
Syntax
Example
Session_start();
The session_start() function must be the very first
thing in your document. Before any HTML tags.
Example 2 (demo_session.php)
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Get PHP Session Variable Values
Next, we create another page called "demo_session2.php". From
this page, we will access the session information
we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new
page, instead they are retrieved from the
session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global
$_SESSION variable:
demo_session2.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Session using print_r
Another way to show all the session variable
values for a user session is to run the following
code:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Output
• Array ( [favcolor] => green [favanimal] => cat )
Modify a PHP session variable
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Output
• Array ( [favcolor] => yellow [favanimal] => cat )
Destroy PHP session
• To remove all global session variables and destroy the session, use
session_unset() and session_destroy()
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo "All session variables are now removed, and the session is
destroyed."
?>
</body>
</html>
Output
• All session variables are now removed, and the session is destroyed.
Exercise 1
Session_start();
_________[“favcolor”]=“Blue”;
Exercise 2
Output the value of the session variable "favcolor".
echo_____________________;
Exercise 3
Create a cookie named "username".
_______________("username", "John", time() + (86400 * 30), "/");
Exercise 4
1.
PHP sessions are created using the . . . . . function.
A) session_starts()
B) sessions_start()
C) session_start()
D) none of above
2.
When you want to store user data in a session use the . . . . array.
A) $_SESSION
B) SYS_SESSION
C) $SESSION
D) $_SESSIONS
Exercise 5
3.
Sessions allow you to
A) store persistent user preference on a site
B) save user authentication information from page to page
C) create multipage forms
D) all of above
Cookies in PHP
• A cookie is often used to identify a user. A cookie is a small file that
the server embeds on the user's computer.
• Each time the same computer requests a page with a browser, it will
send the cookie too. With PHP, you can both create and retrieve
cookie values.
Diff between Session and Cookie
• The main difference between a session and a cookie is that session
data is stored on the server, whereas cookies store data in the
visitor's browser.
• Sessions are more secure than cookies as it is stored in server. Cookie
can be turn off from browser.
Why Cookies used in PHP
• A cookie is often used to identify a user. A cookie is a small file that
the server embeds on the user's computer. Each time the same
computer requests a page with a browser, it will send the cookie too.
steps involved in identifying returning users
• Server script sends a set of cookies to the browser. For
example name, age, or identification number etc.
• Browser stores this information on local machine for future
use.
• When next time browser sends any request to web server
then it sends those cookies information to the server and
server uses that information to identify the user.
Create Cookies
• A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure);
• Name: This sets the name of the cookie and is stored
in an environment variable called
HTTP_COOKIE_VARS. This variable is used while
accessing cookies.
• Value: This sets the value of the named variable and
is the content that you actually want to store.
• Expiry:The expiry date in UNIX timestamp format.
After this time cookie will become inaccessible. The
default value is 0.
• 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.
• Domain: Specify the domain for which the cookie is
available to e.g [Link].
• Security: This can be set to 1 to specify that the cookie
should only be sent by secure transmission using HTTPS
otherwise set to 0 which mean cookie can be sent by
regular HTTP.
Name: it’s the name of the cookie
Value: the value that is to be stored in the cookie. Ex:
username, password, email id
Expire: it’s the expiring time of the cookie since it was
set.
Path: the path of the website where the cookie is
valid.
Domain: The website this cookie is valid for.
Example
• setcookie("username", "Harsha", time()+3600);
• In the above example, the Cookie name is username.
value is Harsha, it expires in 1 hour. It is mentioned in
seconds 60 seconds multiplied by 60 minutes.
• The value of the cookie is automatically URL encoded
when sending the cookie, and automatically decoded
when received (to prevent URL encoding, use
setrawcookie() instead).
Cookie Example
• The setcookie() function must appear BEFORE the <html> tag.
• Example
Cookie Example
<?php
$cookie_name = “stephen";
$cookie_value = “CS";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Output
Cookie 'user' is set!
Value is: CS
Note: You might have to reload the page to see the value of the
cookie.
Modify Cookie
• To modify a cookie, just set (again) the cookie using the setcookie()
function.
Modify Cookie Example
• Modify
Output
Previous Output will be:
Cookie 'user' is set!
Value is: BCA
After Modification:
Cookie ' user ' is set!
Value is: BCA A
Delete Cookie
• To delete a cookie, use the setcookie() function with an expiration
date in the past
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Check if Cookies are enabled
• PHP creates a small script that checks whether cookies are enabled or
not.
• First, try to create a test cookie with the setcookie() function, then
count the $_COOKIE array variable
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0)
{
echo "Cookies are enabled.";
} else
{
echo "Cookies are disabled.";
}
?>
</body>
</html>
Output
• Cookies are enabled
date_default_timezone_set()
• The date_default_timezone_set() function sets the default timezone
used by all date/time functions in the script.
Syntax
• date_default_timezone_set(timezone);
Example
• <?php
date_default_timezone_set("Asia/Bangkok");
echo date_default_timezone_get();
?>
• Output
Asia/Bangkok
simplexml_load_file()
• The simplexml_load_file() function converts the
specified XML file into a SimpleXMLElement object.
• Syntax
simplexml_load_file(file,classname,options,ns,is_prefi
x);
• File – Required. Specifies the path to the XML file
• classname - Optional. Specifies the class of the new object
• options - Optional. Specifies additional Libxml parameters.
LIBXML_COMPACT - Activate nodes allocation optimization
(may speed up application)
LIBXML_DTDATTR - Set default DTD attributes
ns Optional. Specifies a namespace prefix
is_prefix Optional. Specifies a Boolean value.
Example
<?php
$xml=simplexml_load_file("[Link]");
print_r($xml);
?>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Output
• SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] =>
Reminder [body] => Don't forget me this weekend! )
Example1
• <?php
$xml=simplexml_load_file("[Link]");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
Output
Tove
Jani
Reminder
Don't forget me this weekend!