/

How to Utilize PHP Cookie-based Sessions

How to Utilize PHP Cookie-based Sessions

One intriguing application of cookies is cookie-based sessions. Fortunately, PHP provides an effortless way to create a cookie-based session with the help of session_start().

To begin, add the following code snippet to a PHP file and load it in your browser:

1
2
3
<?php
session_start();
?>

Upon executing this code, you will notice a new cookie called PHPSESSID with an assigned value. This cookie acts as the session ID, which will be sent with every subsequent request. PHP utilizes this session ID to identify the session.

Screenshot

Similar to how we utilized cookies, we can now employ $_SESSION to store user-sent information. However, unlike cookies, this data is stored on the server side, while the session ID resides client-side.

To illustrate this, consider the following PHP code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
session_start();

if (isset($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
}
if (isset($_POST['name'])) {
echo '<p>Hello ' . $_POST['name'];
} else {
if (isset($_SESSION['name'])) {
echo '<p>Hello ' . $_SESSION['name'];
}
}
?>

<form method="POST">
<input type="text" name="name" />
<input type="submit" />
</form>

Screenshot

This code works well for simple use cases. However, if you’re dealing with extensive data, incorporating a database becomes necessary.

To clear the session data, you can employ the session_unset() function. On the other hand, if you wish to clear the session cookie, utilize the following code:

1
setcookie(session_name(), '');

tags: [“PHP”, “cookie-based sessions”, “session_start()”, “session_unset()”, “session cookie”]