Session is another way to store information for current user, normally we store sensitive information like, user details, credit card number in session, once user leave the side, all the information are automatically destroyed with session object, we can access session information across all the pages until user keep browsing.
In this tutorial you will learn Session in PHP, creating session object, and reading from session in php code.
$_SESSION['tutorial'] = "WebTrainingRoom";
Session management in PHP application is very similar to Asp.net application, but syntax is very different
We can create session variable assign value to session variable, retrieve values from session variable, then destroy or nullify session variable in PHP.
Before looking at the example of PHP session, you need to understand following php keywords and methods for handling session.
session_start()
Call this function to start the session in PHP
$_SESSION['sessionKey']
This is how you can write session key; php session key is used for holding current user information for that particular session
isset()
check if session variable is already set or not
unset()
unset a session variable
session_destroy()
destroy all the session variables for that current session
Let's learn with example, how to handle php session between pages.
<?php session_start(); if(!isset($_SESSION['userinfo'] )) { $_SESSION['userinfo'] = "WebTrainingRoom"; } $msg = "Hello ". $_SESSION['userinfo']; $msg .= ", Welcome."; echo ( $msg ); ?>
To unset a session in php unset(sessionKey)
<?php unset($_SESSION['userinfo']); ?>
Destroy / nullify all session keys for that particular user.
<?php session_destroy(); ?>
Even if we don’t call the method explicitly, session still will be destroyed after user leave the application, or remain inactive for some specified time, known as session time out.