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:

<?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:

<?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:

setcookie(session_name(), '');