In this PHP tutorial, you will learn all about the Sessions in PHP. We will also discuss how to start a session, create a session, check session, access session and destroy the session
In general, a session is a communication frame between two mediums. A PHP session is used to save data to a server rather than the user's machine. Session identifiers, or SIDs, are numbers that are used to identify each user in a session-based system. The SID is used to associate the user with his information on the server, such as posts, emails, and so on.
We must first start the session before you can store any data in session variables. Simply execute the PHP session_start() method to start a new session. It will start a new session and assign the user a unique session ID.
Example
session_start()
Similar to cookies we must start the session at the beginning of the script using the session_start() function.
Using the $_SESSION[] superglobal array, we may store session data in key-value pairs. During the lifespan of a session, the stored data can be accessed.
Example
session_start();
$_SESSION['user'] = "Roy";
To access a session value, we use the PHP $_SESSION[] superglobal variable. It is often an associative array containing a list of all session values given by the browser in the current request, keyed by session name. Using normal array syntax, the individual session value may be obtained.
<?php
session_start();
$_SESSION['user'] = "Roy";
?>
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1>Hi! <?php echo $_SESSION['user'] ?> Welcome to learnetutorials.com</h1>
</body>
</html>
As we can see in the above example which all page is accessing the session values the function session_start() should be declared. And all those pages should belong to the same domain
If we just want to destroy only a specific session we can use the unset() function with the key of that session as the argument.
Example
session_start();
if (isset($_SESSION['user'])) {
unset($_SESSION['user']);
}
If we want to destroy the whole session we can use the function session_destroy(). The session_destroy() function doesn’t require any arguments. After using the session_destroy() we won’t be able to access any of the sessions.
Example
session_start();
session_destroy();