Php Session Management example

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 in Php with example

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.

Php Session Lifecycle

  • PHP application creates an unique identifier for the current session, which is a random hexadecimal numbers
  • Session creates a file on the server in a temporary directory, and store all registered session variables and their values. So data can be available to all web pages on that site during that visit.
    The temporary file location is determined by a setting in the php.ini file called session.save_path.
  • A cookie PHPSESSID is automatically sent to the user-computer to store unique session identification string

Before looking at the example of PHP session, you need to understand following php keywords and methods for handling session.

Php methods to handle 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

Php Session Syntax with Example

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.

 
Php Session Management
Learn php programming, php web development with free tutorials
Other Popular Tutorials
PHP Examples | Join PHP Online Course