What is session in php?

Last updated 5 years, 7 months ago | 2006 views 75     5

Tags:- PHP

Session in php

A session is a global variable which is used to store users/sensitive information on the server. Each session register a unique session id which is use to fetch stored value. Session store data as an associative array. Once a session variable is created then it is used across multiple page. By default, session variables last until the user closes the browser or leave the site otherwise most of the server terminate the session variable if you are not active more than 24 minutes on the site.

 

Starting a PHP Session

Session gets started by making a call to session_start() function. session_start() function should be the first line in the php page so, make sure session_start() function is first line of your page. session_start() function start a session if none is started before.

session_start();

$_SESSION is use to set a session variable. it is a global variable which store data in an associative array.

$_SESSION['variable_name'] = value;

Now, let's create a page called "test.php" and try some code. in this page we see how to create a new php session and set some session variable and use those variable to print the session data.

<?php
// Starting session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Setting up session variables
$_SESSION["user_name"] = "Adam";
echo "Session variables are set.";

//getting session variable value
echo $_SESSION["user_name"];

?>

</body>
</html>

Note: we can also use print_r() function to print the session data.

print_r($_SESSION);

Now let's create a new page called "test1.php" to get php session variable value in other page and pest the bellow code.

<?php
// Starting session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
//getting session variable value
echo "User name is:-".$_SESSION["user_name"];

?>

</body>
</html>

In the above example we are not defining any session variable instead we just calling one which we created in "test1.php" page.

Modifying the session variable

For changing session variable let's create a new page called "text2.php" and pest the bellow code. In this page we see how to modify session variable.

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it 
$_SESSION["user_name"] = "Tom";
print_r($_SESSION);
?>

</body>
</html>

Destroying PHP Sessions

For destroying a session variable we firstly remove all the global variable by using session_unset() function and then session_destroy() function is use to completely destroy the session variable.

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset(); 

// destroy the session 
session_destroy(); 
?>

</body>
</html>