PHP Sessions

A session is a way to store information (in variables) to be used across multiple pages. Session values are stored at server and contains separate values for every users.

When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state. Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

Start Session & Assign Values

Before any data operation(read/write/unset) on session array, initiate the session with session_start() method

<?php

	//Start the Session for current User
	session_start();
	$_SESSION['Username']='abc@gmail.com';
	$_SESSION['Auth']=true;
?>

Retrieve the Sessions Values

<?php

	session_start();
	
	echo $_SESSION['Username']."
"; echo $_SESSION['Auth']."
"; ?>

Unset & Destroy Session

Good Practice is to unset/destroy the session when they are no more required. it comes under good resource management.

<?php

	session_start();
	
	//remove the Values of $_SESSION
	session_unset();
	
	//close & destroy the complete Session for Current User
	session_destroy();
?>