SESSION in PHP
SESSION in PHP
01
PH 02 03
P Session Session
Short Review Why, where
Fundamental
session is used? Start a session
How its work? Ending a session
Session timeout etc.
3
PHP
Hypertext Preprocessor
4
Session in PHP
5
Why & Where Session is
Used ?
6
How Session Works
7
PHP Session Working (example)
8
Start a PHP Session
o call session_start ( ) :
if the server hasn't seen this user before, a new session is
created
otherwise, existing session data is loaded
into $_SESSION associative array
you can store data in $_SESSION and retrieve it on future pages
9
Start a PHP Session (example)
<?php
session_start(); // Start the session
?>
The session_start() functio
<!DOCTYPE html>
n must be the very first
<html>
thing in your document.
<body>
Before any HTML tags.
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
1
Accessing session data
if (isset($_SESSION["points"])) {
$points = $_SESSION["points"];
print("You've earned $points points.\n");
} else {
$_SESSION["points"] = 0; # default
11
Ending a session
To remove all global session variables and destroy the session,
use session_unset() and session_destroy()
if you may want to start a completely new empty session later, it is best
to flush out the old one
session_destroy();
session_regenerate_id(TRUE); # flushes out session #ID number
session_start();
1
Ending a session (example)
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?>
</body>
</html>
1
Session Timeout
• Because HTTP is stateless, it is hard for the server to know when a user
has finished a session
• ideally, user explicitly logs out, but many users don't
• server automatically cleans up old sessions after a period of time
• old session data consumes resources and may present a security risk
• adjustable in PHP server settings or with session_cache_expire
function
• you can explicitly delete a session by calling session_destroy
1
THANK
S!