php sessions, how to create sessions in php, how to destroy sessions in php, session_start, session_destroy, $_SESSION, sessions in PHP, what is a session

How to create, store and destroy sessions in PHP

User privileges in a system play a key role in determining the pages an authenticated user views and which one should not. A user who is not authenticated is always forced to log in so that he can be known whether he will be granted access to the system.

All programming languages have a way of authenticating users and storing the details of the user such that at any point, it can be known that a certain user accessed the system and performed certain actions.

Sessions in PHP play a key role in authenticating users, keeping track of user’s data in the system as long they are active in the system

In this article, we shall discuss how to create sessions in PHP, how to store sessions in PHP, how to destroy sessions in PHP, and how to keep track of a session in a system.

What is a session in PHP?

According to the official website of PHP, a session is defined as a way in which data is stored uniquely for each individual. It is a simple way in which a user is issued a unique identification when he is authenticated to use the system mostly during login or when one has accessed the system.

The data is stored in a global variable that is passed across multiple pages that make up the system or website.

For a session that is used to identify a user across the system, it must be started.

A session can be terminated after a certain period of interactivity that is defined in the server or it can be terminated by the user when he decides to close the system.

Why are sessions important

Sessions are important in any system since they help in;

  • Identifying the user who has accessed the system
  • Determining the role that the user can play in the system
  • Determining the pages the user can access and which one cannot
  • Ensuring that the user is active in the system, that is, inactivity in the system destroys the system, therefore, preventing unauthorized users from using others' session
  • Passing a user’s information across various pages, that is, the user’s personal profile can be displayed on more than one page as long as the session created is active.

How to create and start a session in PHP

As we highlighted above, sessions are not automatically created in a system, they have to be initialized so that they can be in use.

In PHP, a session is initialized by using the session_start() function. The session_start() function is defined at the top of the page before any other piece of code.

When the session_start() function is called, a session is created for the defined user and a unique identification is assigned.

The following example shows how a session is started in PHP using the session_start() function.

<?php

session_start();   // starting a session

?>

To ensure that the session is active on all the pages in a system or website, the session_start() function must be defined on each page that the session is required.

To check whether sessions are working in your website or they are supported in by your browser or ip address use the session_id() function like shown below

<?php

session_start();   // starting a session

echo session_id(); // unique session for the browser

?>

How to set session variables

Having discussed how to start a session in PHP and also displaying the session value that is defined by default in each browser, we will now discuss how to set custom variables to the session that is already active.

Setting session variables is important since it helps in customizing the system to identify uniquely a particular user who is authenticated such that we can get the profile data using the session once authenticated.

Mostly, the setting of custom session variables is done at the login stage when the user has been authenticated to use the system.

Setting session variables involves defining the session and assigning a value that will be used to uniquely reference it to a certain user or action in the system.

The global variable $_SESSION[] is used while setting session variables.

For example;

<?php

session_start();   // starting a session

$_SESSION["MY_SESSION"]="JOHN DOE"; // defining a session variable called MY_SESSION and assigning it a value JOHN DOE

?>

How to access session variables and values

Once the session variables are set and assigned values, they value of the session is accessed by printing the value assigned inside the global variable $_SESSION[];

For example;

<?php

session_start();   // starting a session

$session= $_SESSION["MY_SESSION"];  // accessing the value of the session

echo $session;

?>

The above code will print JOHN DOE since it is the value that was assigned to the session variable MY_SESSION.

Does PHP allows multiple session variables in one page?

The answer is YES.

You can define as many session variables as possible as long as you distinguish each session variable from the other.

An example of having multiple session variables is as shown below

<?php

session_start();   // starting a session

$_SESSION["MY_SESSION1"]="JOHN DOE"; // defining session 1

$_SESSION["MY_SESSION2"]="[email protected]"; // defining session 2

?>

How to destroy a session in PHP

Sessions in PHP can be destroyed in two ways;

  1. Leaving the session to expire

Once you are authenticated into a system and you fail to actively interact with the system, it will reach a time and the server will destroy the session since the time allocated by the server for the active session will have lapsed.

The time for a session to expire varies from one server to another and can be changed using server settings.

    2. Using session_destroy() function

The session_destroy() function is the one that is used during logout. It unsets the session and the values assigned to the session are removed meaning its usage has come to an end unless it is assigned again.

The following example shows how a session is destroyed and the user redirected to a different page mostly login page

<?php

session_start();   // starting a session

unset($_SESSION["MY_SESSION"]); // unsetting session

session_destroy(); // destroying the session

header("Location:login.php"); // redirecting the user to login page

?>

Login example with session creation

This is a sample login code that sets a session variable once the user is authenticated successfully

<?php

session_start();   // starting a session

if(isset($_POST['email'])){

    $email = trim(mysqli_real_escape_string($con,$_POST['email']));

    $pass = hash("sha256",md5(trim(mysqli_real_escape_string($con, $_POST ['password']))));

    if(mysqli_num_rows(mysqli_query($con,"SELECT * FROM users WHERE email = '$email' AND password ='$pass'")) > 0){

     $_SESSION["USERSESSION"] = $email;

    header("Location:dashboard.php");

    }

    else{

     

    }

}

?>

Conclusion

In the above discussion, we have defined a session as a way of storing unique user data such that it can be used across pages in a system or website. Also, we have discussed how you can start a session using the session_start() function, create session variables using the global variable $_SESSION[], and also assign custom values to a session.

We have also discussed how to access values in a session as long as the session is active and finally demonstrated how to unset and destroy a session using the session_destroy() function.

Hope the above discussion has been helpful. Happy coding