PHP Session

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

PHP Session

• To maintain state of user on web server


sessions are used
Starting session
• A session is started with
the session_start() function.
• Session variables are set with the PHP global
variable: $_SESSION.
• The session_start() function must be the very first
thing in your document. Before any HTML tags.
• Unique SessionID is created for each visitor
• String function session_id() returns current
session_id
• <?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 value of session variables
• all session variable values are stored in the global $_SESSION variable:
<?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>
Destroy a PHP Session
• To remove all global session variables and destroy the session,
use session_unset() and session_destroy():
• <?php
session_start();
?>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy