PHP Session
From w3cyberlearnings
Contents |
What is PHP session
- Session allows the system to store information for later use.
- Session use for checking user authentications.
- Session and Cookie can use together for user authentications or store user information.
start a session
- You are always need to call the session_start() in order to use the session.
<?php session_start(); ?>
to delete or destroy session
- This only delete the session variable
- Use to unset or delete each individual session.
<?php session_start(); if(isset($_SESSION['name'])){ unset($_SESSION['name']); } ?>
destroy all the session
- All everything will be destroy.
- Use this when you want destroy all the user session namely when user logout of the website.
<?php session_start(); session_destroy(); ?>
session example 1
- Set the session.
- call the session.
- assign the session value to the variable.
- Display Result: John
<?php session_start(); $_SESSION['name'] = 'John'; $name = ""; if (isset($_SESSION['name'])) { $name = $_SESSION['name']; } ?> <h3><?php echo $name; ?></h3>
using session to count page
- Using session to count page for every page load.
- Display the total page count according to the page load.
<?php session_start(); // assign session value $_SESSION['id'] = 3232423; $_SESSION['name'] = 'w3cyberlearning'; if(isset($_SESSION['count'])) { $_SESSION['count'] = $_SESSION['count'] + 1; } else { $_SESSION['count'] = 1; } echo 'Name: '. $_SESSION['name'] . '<br/>'; echo 'Id: '. $_SESSION['id'] . '<br/>'; echo 'Total visit this page: '. $_SESSION['count'] . '<br/>'; ?>
pass session value to other pages
- You can assess session information on other page.
first page (page1.php)
<?php session_start(); $_SESSION['id'] = 3232423; $_SESSION['name'] = 'w3cyberlearning'; if(isset($_SESSION['count'])) { $_SESSION['count'] = $_SESSION['count'] + 1; } else { $_SESSION['count'] = 1; } echo 'Name: '. $_SESSION['name'] . '<br/>'; echo 'Id: '. $_SESSION['id'] . '<br/>'; echo 'Total visit this page: '. $_SESSION['count'] . '<br/>'; echo '<a href="page2.php">Second Page</a>'; ?>
second page(page2.php)
- The second page, we assign the session values from the first page
to the variables.
<?php session_start(); $id = 'undefine'; $name = 'undefine'; $count = 'undefine'; if(isset($_SESSION['id'])) { $id = $_SESSION['id']; } if(isset($_SESSION['name'])) { $name = $_SESSION['name']; } if(isset($_SESSION['count'])) { $count = $_SESSION['count']; } echo "This is the second page..<br/>" ; echo 'Name: '. $_SESSION['name'] . '<br/>'; echo 'Id: '. $_SESSION['id'] . '<br/>'; echo 'Total visit this page: '. $_SESSION['count'] . '<br/>'; ?>