PHP 7 Sessions

As we know HTTP is a stateless protocol, when a user requests one page, followed by another, HTTP does not provide a way for you to tell that both requests came from the same user.

The idea of session control is to be able to track a user during a single session on a website.

If you can do this, you can easily support logging in a user and showing content according to her authorization level or personal preferences. You can track the user's behavior, and you can implement shopping cards.

Starting a Session

In PHP, the session_start() function is used to create a client session and generate a session id. Once the session has been created, we can create any number of session variables. The session variable is created in key-value pairs.

Examples

<?php
	session_start();
	$_SESSION['userid'] = '';
	$_SESSION['department'] = '';
?>	




The session_start() takes no arguments and causes PHP either to notice a session id that has been passed to it or create a new session id if not found.

Unset Session Variable

The session_unset() function is used to free all variables in the session. It takes no arguments.

Examples

<?php
	session_start();
	$_SESSION['userid'] = '';
	$_SESSION['department'] = '';
	session_unset();
?>	

Ending Session

The session_destory() function is used to get rid of all session variables information that has been stored. It does not unset any variables in the current script or the session cookie.

Examples

<?php
	session_start();
	$_SESSION['userid'] = '';
	$_SESSION['department'] = '';
	session_destroy();
?>