11. Sessions

A session, or session cookie, is a variable temporarily associated with a specific user. This variable is stored on the server and is associated with a user by means of a unique identifier that is sent to the client's browser. This identifier is a long, random text string that is sent as a cookie to the client's browser. What matters to you is that this variable is only accessible from the server and not from the client.

With this mechanism we can:

  • Protect pages so that only identified users can enter them.
  • Store sensitive information about the visitor that no one can see: name, ID document number, birthday...
  • Increase security. As soon as the user "closes the session" (we'll talk about that later), any previously stored data will be deleted.

Do not confuse session with cookie. They are very similar and it is easy to confuse them. cookies are variables that are also stored in the client's browser, but their content can be seen and their lifetime will be longer.

Creating a Session

Whenever you want to activate a session you must first start the system with session_start(), only once. After that you can use them as many times as you want for whatever you need.

In the example you will see that a session is actually an array called $_SESSION.

session_start();
$_SESSION['nombre'] = 'Goku';
$_SESSION['raza'] = 'Saiyan';

To read the variable.

session_start();
echo $_SESSION['nombre'];
// Goku

Checking if it exists

A session variable is useful to know if the user can enter a specific page.

Let's suppose that our user is registered in our database with the nickname Bulma.

// We create the variable at some point
session_start();
$_SESSION['apodo'] = 'Bulma';

// We check if it exists with isset()
if (isset($_SESSION['apodo'])) {
    // If they are identified, in other words the variable exists, we greet them
    echo 'Hola ' . $_SESSION['apodo'];
} else {
    // Otherwise we redirect the visitor to another page
    header('Location: http://dragonball.jp/login.php');
    die();
}

When you make a redirect with header() always end it with a die() or exit(). You will avoid security problems, you can read more about it at The Daily WTF.

Deleting

The way to delete sessions is with the native function session_destroy().

session_start();
session_destroy();

Important about unset(): You can use unset($_SESSION['clave']) to remove a specific session variable. What you must NOT do is unset($_SESSION), since this destroys the entire superglobal variable and breaks the session system. To destroy the entire session, use session_destroy().

Modifying

It does not change much compared to an array.

$_SESSION['apodo'] = 'Picolo';

Example of a simple login with a protected page

We are going to have 2 pages: one public and one private.

login.php is public. Anyone can enter. The goal is for a user to identify themselves and automatically be redirected to their profile page. The correct data for the form are:

  • Nickname: bulma
  • Password: 123
<html>
    <body>
        <?php
            // We check that the form data arrives
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {

                // Variables that would theoretically be in a database
                $apodoBueno = 'bulma';
                $contrasenyaBuena = '123';

                // Form variables
                $apodo = isset($_REQUEST['apodo']) ? $_REQUEST['apodo'] : null;
                $contrasenya = isset($_REQUEST['contrasenya']) ? $_REQUEST['contrasenya'] : null;

                // We check if the data is correct
                if ($apodoBueno == $apodo && $contrasenyaBuena == $contrasenya) {
                    // If they are correct, we create the session
                    session_start();
                    // IMPORTANT: Regenerate the session ID after login
                    session_regenerate_id(true);
                    $_SESSION['apodo'] = $_REQUEST['apodo'];
                    // We redirect to the secure page
                    header('Location: perfil.php');
                    die();
                } else {
                    // If they are not correct, we inform the user
                    echo '<p style="color: red">The nickname or password is incorrect.</p>';
                }
            }
        ?>
        <form method="post">
            <p>
                <input type="text" name="apodo" placebolder="Apodo">
            </p>
            <p>
                <input type="password" name="contrasenya" placebolder="Contraseña">
            </p>
            <p>
                <input type="submit" value="Entrar">
            </p>
        </form>
    </body>
</html>

perfil.php is a page that no one can enter without going through the previous page.

<?php
// We check if the nickname session exists
session_start();
if (!isset($_SESSION['apodo'])) {
    // Otherwise we send them back to login.php
    header('Location: login.php');
    die();
}
?>
<html>
    <body>
        <!-- We greet -->
        <h1>Bienvenido <?= $_SESSION['apodo'] ?></h1>
        <!-- Button to close the session -->
        <a href="logout.php">Cerrar sesión</a>
    </body>
</html>

logout.php: To complement it, a page can be created to close the session.

<?php
// We start the sessions
session_start();
// We destroy the sessions
session_destroy();
// We take them to login.php
header('Location: login.php');
die();

With this we have a simple security system for our pages.

Security: Regenerate the session ID

Important for security: You must always use session_regenerate_id(true) after a successful login or when you change the user's privilege level. This prevents session fixation attacks, where an attacker tries to force the victim to use a known session ID.

The true parameter in session_regenerate_id(true) indicates that the old session file must be deleted, not just a new one created.

When to use session_regenerate_id(): - After a successful login. - When the user changes their password. - When the user's privileges increase (for example, from a normal user to an administrator). - Periodically during long-lasting sessions (every 15-30 minutes).

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.