Sessions Issues

Hello,

I’m trying to make a page in php, and since this is my first complete page in php I’ve run into a problem and I have no idea what it could be. It’s a session. I have a login on the page, where when everything goes fine it executes the code see attachment. When I try to do the session the same way it doesn’t want to save data to it because when I initialize the session in another file it is null, what could it be.

Code description

In one document I am trying to get the id from session user_id which is fine I get the id and this session works fine, then I call a function that gets the data from the database and that should be fine too, then I try to save this data to the session so $_SESSION[‘user_data’] = $get_user_data;. Next in another file I initialize this session $userData = $_SESSION[‘user_data’]; and then I try to print its data to the page, but the session is empty. I’ve tried to do this in several pages of my project and sometimes it works, and sometimes I have to requirer directly the file from the given logic so the session is there for nothing. I am lost in this.

Thank you.

It would be better to put the code between the </> preformatted text like the following

// Process the login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if the submitted CSRF token matches the one stored in the session
    if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        // Sanitize the username and password input
        $username = strip_tags($_POST['username']);
        $password = $_POST['password'];

        // Verify the user's credentials
        if ($login->verify_credentials($username, $password)) {
            // Generate a secure login token
            $token = bin2hex(random_bytes(32));
            // Store the login token in the database
            $login->store_token_in_database($_SESSION['user_id'], $token);

            // Set a secure cookie with the login token
            setcookie('login_token', $token, [
                'expires' => strtotime('+6 months'),
                'path' => '/',
                'domain' => DOMAIN,
                'secure' => true,
                'httponly' => true,
                'samesite' => 'Lax'
            ]);

            // Store the login token in the session
            $_SESSION['login_token'] = $token;

            // Redirect the user to the dashboard
            header('Location: dashboard.php');
            exit;
        } else {
            // log error message for invalid username or password
            $error = 'Invalid username or password';
            error_log("Login error: " . $error);
        }
    } else {
        // Display an error message
        $error = 'Invalid CSRF token';
        error_log("Login error: " . $error);
        $error = 'An error occurred. Please try again.';
    }
}

That was just an example, but people here will be able to help you out better.

When you do post your actual code in the forum, identify the filename of each piece of code.

The code for any page should be laid out in this general order -

  1. initialization
  2. post method form processing
  3. get method business logic - get/produce data needed to display the page
  4. html document

The post method form processing code and post method form for any operation should be on the same page. The only redirect you should have anywhere in your code is upon successful completion of the post method form processing code and it should be to the exact same URL of the current page. If you want to display a one-time success message, store it in a session variable, then test, display, and clear that session variable at the appropriate location in the html document. To allow the user to go to any other page, provide navigation links.

The only piece of user related data that should be stored in a session variable upon successful login is the user id (which is one of the pieces of data you are storing.) You should query on each page request to get any other user related data, and store it in an approximately named array variable, not a session variable.

A session variable is an input to the code on a page. If it is a ‘required’ input, you must validate that it is at least set before using it. If a ‘required’ input is not valid, you would setup and display an error message, instead of running code that’s dependent on that input.

The only database exceptions you should catch and handle in your code are for user recoverable errors, such as when inserting/updating duplicate user submitted data. In all other cases, simply let php catch and handle any database statement exception, where php will use its error related settings to control what happens with the actual error information, via an uncaught exception error (database errors will ‘automatically’ get displayed/logged the same as php errors.)

A post method form is used when performing an action on the server, such as inserting, updating, or deleting data, sending an email, … What action is the first piece of code performing?

htmlspecialchars() is an output function. Do NOT apply it to values being put into variables, because it changes the meaning of the data. Apply it only to values that are being used in a html context, right before using them.

Data that is an input to a function should be supplied as a call-time parameter. This makes the function general-purpose, i.e. you can call it with data gotten from anywhere. For your display_user() function, since it is hard-coded to get the data from a session variable, it cannot do anything else. What if you have a page that allows an administrator to edit user data. If the display_user() function accepted its input data as a call-time parameter, you can use it to either display the current user’s data or any user’s data.

Functions should return the result they produce to the calling code. This allows the result to be used in any context - web page, email body, api response, …

There’s generally no need to free-up prepared query statements, result sets, or close database connections in your code since php destroys all resources when your script ends.

Hi,
I guess I misspoke. Since I can upload only one image to this page, I have combined 3 images into one. What you can see above are 3 different code files. Even the images are not important I just wanted to give an example of what my code looks like. My problem is that let’s say I have file one “example1.php” and file two “example2.php” and I am trying to use session to send the information from “example1.php” to “example2.php”. In both files I have a requirnuty file where I have the session settings. The problem is that the data is not overwritten so in the second file the session is null. I don’t understand why this is happening when in the login file see above as I posted it works and in the new file it doesn’t work anymore and I have to requirnout the file directly i.e. “example1.php” to "example2.php.

Code example:

<?php

// Načtení souboru index.inc.php

require_once $_SERVER['DOCUMENT_ROOT'] . '/TIS/includes/index.inc.php';

/**

 * Funkce pro zobrazení karet filmů na úvodní stránce.

 *

 * @return void

 */

function display_films() {

    // Získání pole filmů z $_SESSION

    $films = $_SESSION["films"]; // Here is inicializaton of session but its null. Its is working only because  of require_once $_SERVER['DOCUMENT_ROOT'] . '/TIS/includes/index.inc.php';f 

    // Výpis karet filmů

    echo "<div class='row mt-5'>";

    foreach ($films as $film) {

        echo "<div class='col-md-4 mb-3'>";

        echo '<form action="includes/film.inc.php" method="get">';

        echo "<button type='submit' class='card h-100 btn btn-link p-0' name='film_id' value='{$film['id']}'>";

        echo "<div class='bg-image hover-zoom'>"; // Přidána třída hover-zoom

        echo "<img class='card-img-top w-100' src='{$film['image_url']}' alt='{$film['title']}'>";

        echo "</div>";

        echo "</button>";

        echo '</form>';

        echo "</div>";

    }

    // Zavření řádku

    echo "</div>";

    echo "</div>";

    // Přidání jQuery pro zoom efekt s transition a zvětšením o 3 px

    echo <<<HTML

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

    <style>

        .hover-zoom img {

            transition: transform 0.3s ease; /* Transition time 0.3s s efektem ease */

        }

    </style>

    <script>

        $(document).ready(function(){

            // Přidání zoom efektu na obrázek s třídou hover-zoom

            $(".hover-zoom img").hover(function(){

                $(this).css("transform", "scale(1.03) translate(3px, 3px)"); // Zvětšení obrázku na 110% s přesunutím o 3px

            }, function(){

                $(this).css("transform", "scale(1)"); // Návrat obrázku na původní velikost

            });

        });

    </script>

HTML;

}

?>

File number two

<?php

// Načtení konfigurace relační proměnné session

require_once $_SERVER['DOCUMENT_ROOT'] . '/TIS/includes/config_session.inc.php';

// Kontrola, zda je uživatel přihlášen

if (!isset($_SESSION['user_username'])) {

    // Pokud uživatel není přihlášen, přesměruj ho na přihlašovací stránku

    header('Location: login.php');

    die();

}

// Pokud je uživatel přihlášen, získej potřebné informace

require_once $_SERVER['DOCUMENT_ROOT'] . '/TIS/includes/dbh.inc.php';

require_once $_SERVER['DOCUMENT_ROOT'] . '/TIS/model/index_model.inc.php';

// Získání uživatelského jména z relační proměnné session

$userUsername = $_SESSION['user_username'];

// Získání role uživatele z databáze a uložení do relační proměnné session

$user = get_user_role($pdo, $userUsername);

$_SESSION["role"] = $user;

// Získání seznamu filmů a uložení do relační proměnné session

$sort_by = 'none';

$films = get_films($pdo, $sort_by);

$_SESSION["films"] = $films;

?>


Here is image of codes for better view.

Ignoring that you shouldn’t even be using multiple pages to accomplish displaying specific content, you have a top-down system-wide problem, some session data doesn’t work, but you are only showing us two small pieces of the problem, the code setting the session variable and the code using the session variable. Somewhere in the code between those two pieces is where the problem lies.

You either have some code clearing the session variable, the links/redirects are changing either the protocol, host-name, or path in the URL so that session cookie no longer matches and a new session is created each time, or because you are rolling your own session id values, the session ids don’t match up and a new session is created each time. We cannot tell you which one of these things, or all of them, is causing the problem until you post all the relevant code. Post all your code, less any database connection credentials to avoid wasting further time in trying to solve this problem.

Sponsor our Newsletter | Privacy Policy | Terms of Service