Search code examples
phpsession-variablessession-state

Don't understand why $_SESSION is needed


I tried to create a login form from an example. I made it works but I don't understand.

Why $_SESSION['umsco'] is required and why should I assign the $username variable to it. I also do not understand if conn->close() required and what is the $result variable.

// I include the database file so we can get the information from there and apply it in here as well.
include "dbc.php";

// here we select the variables we want from the table 'members'.
$sql = "SELECT id, firstName, lastName FROM members";

// here we do something that I dont really know but this is standard procedure.
$result = mysqli_query($conn, $sql);

// declaring username
$username = $_POST["username"];
$password = $_POST["password"];


// my result thing, again, standard procedure.
$result = $conn->query($sql);

// we insert all values in row, standard procedure.
$row = $result->fetch_assoc();

// here we check if the username is the same as the database.
if ($username == $row["firstName"]) {
    // if it's correct then we start a session
    session_start();
    // we give a session some random letters or numbers and set it to $username, not exactly sure why, but it wont work without it.
    $_SESSION['umsco'] = $username; 
    // we change the location to secrect.php
    header("location: secret.php");
}

// we close the connection, not sure if this is needed, but it seems logical.
$conn->close();


Solution

  • I advise you to always implement session_start()at the beginning of your code to avoid bad behavior.


    What is a session

    To understand, you must understand what a PHP session is.

    A session is a way to keep variables on all pages of your site for a current user.

    How it work

    First you must ask PHP to initialize the session. For doing this, you must add session_start() at the beginning of your code.

    When the server responds to the client, it append a cookie called PHPSESSID who contains the unique session identifier of the user.

    At every request, the browser sends this cookie to the server so that php can recover the session from the hard disk of the server.

    The most commun way to register a session variable is $_SESSION['key'] = $value;.

    Final answer

    To end, the line $_SESSION['umsco'] = $username; store the username of the user in his session until.

    In secret.php you probably check whether this value is assigned or if the session exists to check if the user is logged in. That's why it's mandatory, otherwise a login form would have no meaning.

    Another ressource : Is closing the mysql connection important?