How to use session in php code - with complete example

How to use session in php code - with complete example

PHP Session

PHP session is used to store information in a variable temporarily to be used across multiple pages. PHP session creates unique user id for each browser to recognize the user and avoid conflict between multiple browsers.

Before store information in a session, you have to start PHP’s session handling. This is start at the beginning of your PHP code (top of the page), and must be done before any text, HTML, or JavaScript is sent to the browser.

To start the session, you call the session_start() function in your each file:

<?php
session_start(); // start session!
?>

session_start() starts the session between the user and the server, and allows to store value in $_SESSION which can be accessible in other pages. In your second file, you call session_start() again which this time continues the session, and you can then retrieve values from $_SESSION with the variable name of session. For example:

Loading...

First Page:

<?php
session_start(); // start session!
$_SESSION['userName'] = 'Tony';
?>

Second Page:

<?php
session_start(); // start session!
echo 'User Name is :'.$_SESSION['userName'];
?>

Output of second page is:

User Name is : Tony

When you create the logout page then you have to remove all global session variables and destroy the session, use session_unset() and session_destroy():

<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>

Related posts

Write a comment