Home  >  Q&A  >  body text

PHP session not saved when navigating between pages on my website

Why is my php session not saved when I browse website pages?

I'm creating a website that uses a simple username-password pair to allow administrators to authenticate themselves on the login page. To do this, first a session is created when the user reaches the home page, then when they click on the login button, they are redirected to a form to enter the username and password, then the form is sent to another one via POST method to verify the username and password If the page is valid, put a variable in the session containing the logged in admin username, then redirect to the admin dashboard, verify that the variable is set to check if it is indeed an admin on the page.

As explained in the title, the main problem is that when I test the home page a session does get created, but when I click the link to the login form the session seems to be destroyed, even though I remove or neutralize anything that might cause instructions to do so.

Small php snippet to start the session on the homepage (main.php)

<?php 
        session_start(['cookie_lifetime' => 86400]); 
        $_SESSION["start"] = time();
        error_log("Test de session : ".session_status()." | ".$_SESSION["start"]."; \n", 3, "log1.txt"); //puts in the log the session status and the content of the variable assigned above.
        if (!is_writable(session_save_path())) {
            error_log('Session path '.session_save_path()." is not writable for PHP; \n", 3, "log1.txt"); 
        } else {
            error_log('Session path '.session_save_path()." is writable for PHP; \n", 3, "log1.txt");
        }
        ?>

I tried overriding the cookie lifecycle as shown above, getting a snippet of the answer to this question to see if the folder was writable and if the session was created. The log always returns to the home page:

Test de session : 2 | 1684946314; 
Session path C:\MAMP\bin\php\sessions\ is writable for PHP;

(The first line | the number after it is the expected timestamp).

The only php code snippet in the login form (connexion.php)

<?php 
        if (isset($_SESSION["logged_admin"])) {
            header("Location: auth.php");
            exit();
        }

        error_log("Test de session : ".session_status()." | ".$_SESSION["start"]."; \n", 3, "log1.txt");
        if (!is_writable(session_save_path())) {
            error_log('Session path '.session_save_path()." is not writable for PHP; \n", 3, "log1.txt"); 
        } else {
            error_log('Session path '.session_save_path()." is writable for PHP; \n", 3, "log1.txt");
        }
    ?>

I've put the first if there so that logged in admins are redirected directly to the dashboard if they are already connected. The lines after that perform the same test as in main.php, but this time return in the log:

Test de session : 1 | ; 
Session path C:\MAMP\bin\php\sessions\ is writable for PHP;

This indicates that the session has been destroyed and all its variables are unset.

Part of the code in the php file (auth.php) responsible for checking the username and password provided in connection with the session usage

<?php 
        error_log("\n\n------- [AUTH START ".date(DATE_RFC2822)." ] -------\n", 3, "log1.txt");
        $fail = 0;

        /*if (isset($_SESSION["logged_admin"]) && isset($_SESSION['start']) && (time() - $_SESSION['start'] > 1800)) {
            session_unset(); 
            session_destroy(); 
            session_start(['cookie_lifetime' => 86400]);
            $_SESSION["start"] = time(); 
            error_log("Session expirée (connecté + de 30 min);\n", 3, "log1.txt");
            echo "Votre session a expirée. Veuillez vous reconnecter.";
            $fail = 1;
            goto fail;
        }*/ //code that checks if a session is loaded during too much time and if yes, destroys it. I've put the code in a comment so it normally shouldn't be executed by the server.

        error_log("Test de session : ".session_status()." | ".$_SESSION["start"]."; \n", 3, "log1.txt");
        if (!is_writable(session_save_path())) {
            error_log('Session path '.session_save_path()." is not writable for PHP; \n", 3, "log1.txt"); 
        } else {
            error_log('Session path '.session_save_path()." is writable for PHP; \n", 3, "log1.txt");
        } //Here's once again the similar tests done in the other files.

        if (isset($_SESSION["logged_admin"])) {
            error_log("L'administrateur est déjà connecté;\n", 3, "log1.txt");
            goto fail;
        }

        //Other stuff that verifies if the data sent with POST method is there and connecting the local server to the database i use.

        $Accounts = $AccountsQuery->fetchAll(); //Converts the data i've received via a SQL query
            foreach ($Accounts as $Compte) {
                if ($Compte["login"] == $login && $Compte["mdp"] == $mdp) {
                    $_SESSION["logged_admin"] = $login; //if a username-password couple from the registered admins corresponds to the couple sent via the log in form, the username retrieved from the log in form ($login) is associated to the session's array.
                    error_log(session_status()."; \n", 3, "log1.txt");
                    error_log("Login et mot de passe valides | ".var_dump($_SESSION["logged_admin"])." est désormais connecté sur la session ".session_id()." ;\n", 3, "log1.txt");
                goto fail;
            }
        }
        $fail = 1;
        error_log("Login et mot de passe invalide; \n", 3, "log1.txt");
        echo "L'identifiant ou le mot de passe fourni est invalide."; ?>

The log returned by executing the file after submitting the form:

------- [AUTH START Wed, 24 May 2023 16:49:17 +0000 ] -------
Test de session : 1 | ; 
Session path C:\MAMP\bin\php\sessions\ is writable for PHP; 
PDO set up for authentification;
1; 
Login et mot de passe valides |  est désormais connecté sur la session  ;
Authentification réussie le Wed, 24 May 2023 16:49:17 +0000 - British GMT hour ----------------------- [AUTH END]

Since I have put the registered admin credentials into the form, the authentication itself succeeds, but after clicking to access the login form, the session created in the home page turns out to be still deleted, so the username cannot be put in Logged-in administrators in the $_SESSION array.

if structure prevents unauthorized users from accessing admin-only dashboard content (dashboard.php)

<?php if (isset($_SESSION["logged_admin"])) { ?>
     //If there's a logged-in admin, shows up the dashboard with the admin-stuff to do.
<?php 
    } else {
        echo "Vous ne pouvez pas accéder à cette page car vous n'êtes pas connecté. Veuillez vous rediriger vers la page principale.";
    }; 
    ?> //Else shows the user on the page that he isn't logged-in.

Excerpts from two configuration files for PHP components used in my server (php 8.1.0)

php.ini-development

...
;
; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process's umask.
; https://php.net/session.save-path
session.save_path = "tmp/"

php.ini-production

;
; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process's umask.
; https://php.net/session.save-path
session.save_path = "tmp/"
The

session.save_path parameter is apparently uncommented in both. However, it is not the path returned by the session_save_path() function.

P粉316890884P粉316890884375 days ago513

reply all(1)I'll reply

  • P粉588152636

    P粉5881526362023-09-14 09:19:36

    https://www.php.net/manual/en /function.session-start.php

    Every time a new page is loaded, it is a different HTTP request. A session must be started on every HTTP request, so you must add session_start() to every page.

    I recommend creating a single header file that is included in all pages, it is also useful for setting other things needed on all pages, such as redirecting to the login screen if the user is not logged in.

    reply
    0
  • Cancelreply