1

When the user logs in, the first page of retrieving data from the session is fine. When I go to another page, the session is blank.

I have found out that the session id changes, when the user logs in and is getting the first user page which is card.php. When going to for instance subscription.php, the session id is different for whatever reason.

I have tried to list useful code underneath:


log-user-in.php:

<?
    session_start();
    include('includingThis.php');

    unset($_SESSION["emaillogin"]);

    // Sørg for at e-mailen er undercased
    $email = addslashes($_POST[email]);
    $password = addslashes($_POST[pass]);


    if ($email == "" || $password == "") {
        header("Location: login.php?e=3");
        exit;
        die();
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header("Location: login.php?e=4");
        exit;
        die();
    }



    $email = strtolower($email);


    // TJEK OM BRUGEREN FINDES
    if ($stmt = $con->prepare("SELECT email, pass, uid, profilepic, paid FROM stnd_users WHERE email=?")) {


                /* bind parameters for markers */
                $stmt->bind_param("s", $email);

                $stmt->execute(); 
                $stmt->bind_result($em, $pa, $u, $pp, $pai);

                    // Loop through each row in the result set
                    while ($stmt->fetch()) {
                        $gottenEmail = $em;
                        $gottenPass = $pa;
                        $uid = $u;
                        $profile_pic = $pp;
                        $paid = $pai;
                    }

                    $stmt->close();         
    }



    if ($gottenEmail == "" || $gottenPass == "") {
        header("Location: login.php?e=5");
        exit;
        die();
    }



    if (password_verify($password, $gottenPass)) {
        // BRUGER LOGGES IND

        // NÅR BRUGEREN FINDES, OG KODEN ER KORREKT
        if ($uid != "") {

            $_SESSION["user"] = $uid;

            if ($paid == "true") {

                // Bruger har betalt
                if ($profile_pic == "true") {
                    header("Location: user/card.php");
                    exit;
                } else {
                    header("Location: user/profilepic.php");
                    exit;
                }

            } else {

                // Bruger har IKKE betalt   
                header("Location: user/inactive.php");
                exit;
            }


        } else {
            //DER ER SKET EN FEJL, INTET UID
            header("Location: login.php?e=6");
            exit;
            die();
        }


    } else {
        //Oplysningerne er ikke korrekte, har du tastet rigtigt?
        // (Kode ikke korrekt)
        header("Location: login.php?e=5");
        exit;
        die();
    }


?>
M. Holm
  • 53
  • 6
  • 1
    Well, you either don't call the `session_start()` everywhere it's needed or you call `session_destroy()` somewhere where you shouldn't. – Rikudou_Sennin Jun 20 '19 at 14:00
  • I haven't used `session_destroy()` as I didn't know it was a thing - and why would it work the second time, if I had done that? First try always not working, second try always working, for no reason at all! – M. Holm Jun 20 '19 at 14:03
  • Well, then show us some more code, we don't know what's wrong with your code if you don't show us the code. – Rikudou_Sennin Jun 20 '19 at 14:06
  • @Rikudou_Sennin well I am only using two user pages, one that always works and one that only works after it hasn't worked, when trying to debug. Both pages have session_start(); as the beginning of the page and both is retrieving the session["user"] into a variable but the second page only works after it hasn't. Even if I try using echo right after creating the variable of the session, it is empty so I do not think more code is usable at this point. – M. Holm Jun 20 '19 at 14:31

2 Answers2

1

After the header redirect, end the current script using exit();

Maybe you misssed something from this answer:

PHP session lost after redirect

You can also check the session status detailed here :

Check if PHP session has already started

https://www.w3schools.com/php/php_sessions.asp

Or, just as Rikudou_Sennin pointed out, you must have omitted accidentally somewhere the php line session_start(); before defining or accessing the session variable/s.

Dukai Károly
  • 42
  • 1
  • 7
  • Well, I have a lot of user pages, but I have tried only focussing on two pages. Index.php and subscription.php - both only user pages and both gets the session (uid) of the user. When I login the first time, I am shown index.php - no problem. I even added code that displays the session in index.php. When I try to go to subscription.php (no redirect here, just clicking a link) the session is empty. If I try to login again and do it all again it works. That is why it is so weird!? I want it to work the first time too :( – M. Holm Jun 20 '19 at 14:23
  • Did you put `exit();` on the end of any of your scripts? If the first script not exited, and you open the second script, then again you open the first script then again the second, i think its logical that the session is working on the second try and lets you use the stored value ... – Dukai Károly Jun 20 '19 at 14:37
  • When the session is empty, the user is redirected to `logout.php` where the session is destroyed (even though there isn't any) and I have `exit();` after every redirect I make. – M. Holm Jun 20 '19 at 14:43
  • Do not use `session_destroy()` or the session data will be destroyed https://www.php.net/manual/en/function.session-destroy.php – Dukai Károly Jun 20 '19 at 14:52
  • Dukai, that is the purpose when logging out, to destroy the session, that is why i use it there. – M. Holm Jun 20 '19 at 15:22
  • Ok,that is correct. Do you have different scripts for the login page,login processing and protected pages? You should not head directly and process the login data on protected pages...would you please show these three scripts. – Dukai Károly Jun 21 '19 at 05:52
  • I have added the script for when I am logging in users – M. Holm Jun 21 '19 at 09:54
  • If it can be of any help, first when I login, the `session_id` changes between pages. So the session_id which I have a saved something in the session is changed and therefore the error is happening. Do not know why it is changing. After changing one time, it just stays the same? – M. Holm Jun 21 '19 at 10:00
  • Do you have separate loginform/login processing/secured page scripts? – Dukai Károly Jun 22 '19 at 10:54
0

1st You should save user credentials that you wants for further usage if User inputs for username and password matched with DB records with $_SESSION

include("..\includefiles\db.php");

$email =$_POST["email"];
$password = $_POST["password"];

$sql = "SELECT * FROM member WHERE email ='$email' AND password =  '$password'";
$result = mysqli_query ($con,$sql);
if($row = mysqli_fetch_array($result)){


 $_SESSION['ID'] = $row['id'];
 $_SESSION['NAME'] = $row['name'];
 $_SESSION['ROLE'] = $row['role'];

 if($_SESSION['ROLE']=='a'){

  header("Location: ..\dashBoard.php");
}else{
  header("Location: ..\index.php");
}

After saving sessions all you have to do is to start the session with

session_start()

function in each page. Please note that session_start() function must be the very first thing in your document. Before any HTML tags.And then check the availability of the session and if session not set redirect to the login page. See the below code.

<?php
    session_start();

   if(isset($_SESSION["ROLE"])){    

   }else{
           header("Location: login.php");
       }

   ?>   
      <!DOCTYPE html>

Hope that you may able to grab something from this.

Nipun Tharuksha
  • 2,186
  • 3
  • 10
  • 33