How to Use Sessions in PHP Web Applications

How does session work in web applications, covers basic concepts of session management. If you are new to web sessions, you should read that post first.

This article follows code centric approach i.e. it contains different code samples with brief description. It covers: how to create a session in PHP, how to put some data in session, how to get data from session, how to remove specific data element from session or all of the session data at once. Consider it a reference article of code samples of PHP Sessions.

How to Create New Session in PHP

The below PHP file i.e. create_session.php creates new session at web server when the page is accessed from browser. session_start() method is used to create a new session. When session is created, a unique session ID is generated, we can read the value of session ID by calling session_id() function.

Server send the generated session ID to browser where it is stored as cookie, named PHPSESSID. When user send another request, browser automatically put that PHPSESSID cookie in request. The session ID is used by web server to identify specific user's session.

<!DOCTYPE HTML>
<html>
<head>
    <title>Create Session</title>
</head>
<body>

<h3>Session Created at Web Server. </h3>

<?php
session_start();
echo "Session ID = " . session_id();
?>

</body>
</html>

When the page is accessed, it shows following output in browser:


Lets dig further. Before opening the web page, if you enable Developer Tools (using Ctrl+Shift+I in Chrome), the Network tab display the details of HTTP request and response packets. I have drawn blue rectangle around Set-Cookie header. When session_start() is initially called to create a new session, the function put Set-Cookie header in HTTP response. When browser receive Set-Cookie header in HTTP response, it work like an instruction for browser to create a new cookie named PHPSESSID, that contains session ID of the particular user.

When session is created at server, Apache creates a new file for each session in which it saves the data that web developer has saved in the session. (we would shortly see how to save data in the session). You must know where the file that stores session data is located, if you using WAMP, see below figure for session files location:



There is no benefit of creating session at server if we do not save some data in it. To keep it simple, I have not stored any data in the session in above code sample. Next section explains, how to save data in the session.

How to Save Data in Session in PHP

Below code sample i.e. save-data.php save some data into session.

save-data.php
<!DOCTYPE HTML>
<html>
<head>
    <title> Save Data in Session </title>
</head>
<body>

<h3>Save data in Session</h3>

<?php
    session_start();
    $numbers = array(1, 2, 3, 4, 5);

    $_SESSION['city'] = "Lahore";
    $_SESSION['numbers'] = $numbers;

    echo "Some data saved into session.";
?>

</body>
</html>

Lets see what the above code do. We must call session_start() function in all PHP pages where we want to use sessions. What this function do? When session do not exist already, it creates new session (as I explained above section). If session_start() function finds PHPSESSID cookie in HTTP request, its mean the session was created in some previous web request from same user. So the function use PHPSESSID to decided from which file the user session data shall be loaded to $_SESSION array. So after the session_start() functions is called, the $_SESSION array would contain the previously saved data in the user session.

In previous section, we created a session but didn't saved any data in it. So after the session_start() function is called in above code sample, the $_SESSION array would be empty. We may store any type of data in session e.g. int, double, strings and arrays, etc. To keep it simple, I have stored only a string i.e. city name and an array of integers in above code sample. Once the web server has done with processing the request and response is sent to the browser, the server automatically write the contents of updated $_SESSION array in user specific session file i.e. C:\wamp\tmp\sess_iiifueend25pukqipbqjp0amc7. In next request from same user, the data stored in file is loaded back into $_SESSION array. Writing array contents back to file is done by server, so we don't need to worry about it. We just put some data into $_SESSION array and read it back from any other page in current or subsequent requests.


Please note that, I have saved value of city and an array of integers just to demonstrate how data is stored in session. In reall applications, we store user specific data in session e.g. user ID, her email, preferences, recently visited products, etc. So mostly, each user session data is different from other users.

How to Get Data from Session in PHP

When a user access a web page that reads some data from session, see code of get-data.php given below, session_start() automatically loads session data stored in previous requests into $_SESSION array, as explained earlier. Data that is stored in session can be retrieved in any page of the web application becaues all pages refers to same session for a particular user requests, as explained in below figure.

Below code get the city name and array of integers from session that we stored earlier. I have displayed data saved in session in user browser using echo function, we may use the session data the way we want.

<!DOCTYPE HTML>
<html>
<head>
    <title> Get Data from Session </title>
</head>
<body>

<h3>Get data from Session</h3>
<?php
    session_start();
    $nums = $_SESSION["numbers"];
    $city_name = $_SESSION["city"];

    echo $city_name;
    foreach($nums as $num)
        echo "<br/> $num ";
?>
</body>
</html>

Below figure shows the output of above code.

How to Remove Data from Session in PHP?

Session is user specific storage at server, we may need to remove some data from session when its no more required. As I explained above, session data is loaded from file into $_SESSION array by session_start() when request comes from browser. $_SESSION is an associative array, so we can add and remove elements from $_SESSION array as we do using normal PHP arrays. Earlier we looked at how to add new values into session, below code removed city attributes from user session.

<!DOCTYPE HTML>
<html>
<head>
    <title>Read</title>
</head>
<body>

<h1> Removing data from session. </h1>

<?php
session_start();

if (isset($_SESSION["city"])) {
    unset($_SESSION["city"]);
    echo "city attribute removed from session";
} else {
    echo "city key do not exist in session.";
}
?>
</body>
</html>

Before removing some attribute from $_SESSION array, its good practice to first ensure the attribute exist in session, to avoid "index undefined error". So first, I checked whether the "city" key exist in $_SESSION array using isset method. If its found, only then I removed it from session calling unset function. As "city" key was added earlier, so the above code shows following output:


It indicates, the city key is now removed from session. In this way, we can remove other attributes from the session. After the "city" key is removed, calling remove.php page again would show following output:


If you want to remove the session data completely. You can call session_destroy() function, it would remove the user session at server side. That means, all the data saved in session would be destroyed. Below is the code for remove-all.php:

<!DOCTYPE HTML>
<html>
<head>
    <title>Remove Session</title>
</head>
<body>

<h1> Remove Session </h1>

<?php
session_start();
session_destroy();
echo "User session destroyed at session.";
?>

</body>
</html>

Here is the outpt of above code:

Comments

  1. Your good knowledge and kindness in playing with all the pieces were
    very useful. I don’t know what I would have done if I had not
    encountered such a step like this.

    white label website builder

    ReplyDelete

Post a Comment