PHP Sessions
While cookies can be used to store data, they do have some security issues. Since cookies are stored on the user's computer, an attacker can easily change the cookie content to inject potentially harmful data into your application, potentially breaking it.
In addition, every time the browser sends a URL to the server, all of the website's cookie data is sent to the server as part of the request. It means that if you store five 4KB
cookies on a user's system, the browser must upload 20KB
of data each time the user visits a page, which can slow down your site's efficiency.
The PHP session can be used to solve both of these problems. Instead of storing data on the user's device, a PHP session saves it on the server. Any user in a session-based environment is marked by a unique number known as a session identifier, or SID. This one-of-a-kind session ID is used to connect each user's personal details on the server, such as emails and posts.
Getting a PHP Session Started
You must first start the session before you can store any data in session variables. Simply call the PHP session start()
function to start a new session. It will start a new session and assign the user a unique session ID.
The PHP code in the following example simply creates a new session.
<?php
// Starting session
session_start();
?>
The session_start()
function first checks for the existence of a session ID to see if one already exists. If it detects one, i.e. if the session has already started, it sets up the session variables; if it does not, it creates a new session ID.
Session Data Storage and Access
The $_SESSION[]
superglobal array will hold all of your session data as key-value pairs. During the duration of a session, the stored data may be retrieved. Take a look at the script below, which introduces a new session and sets two session variables.
<?php
// Starting session
session_start();
// Storing session
// data
$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker";
?>
Simply recreate the session by calling session start()
and then passing the corresponding key to the $_SESSION
associative array. To access the session data we set in our previous example on the same web domain from any other page.
<?php
// Starting session
session_start();
// Accessing session
// data
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];
?>
Getting Rid of a Session
Simply unset the corresponding key.
The corresponding key should be that of the $_SESSION
associative array to extract specific session data, as shown in the following example:
&ly;?php
// Starting session
session_start();
// Removing session
// data
if(isset($_SESSION["lastname"])){
unset($_SESSION["lastname"]);
}
?>