2

Here is my code for setting sessions in user-authentication.php:

session_start();
$_SESSION['admin_name'] = $name;
$_SESSION['sbc_admin'] = "y";
$_SESSION['admin_email'] = $email;

header("Location:includes/user-auth.php");

and here's the code to check whether sessions are set or in user-auth.php:

session_start();
    if (isset($_SESSION["sbc_admin"])) {
        $admin = $_SESSION["sbc_admin"];
        $name = $_SESSION["admin_name"];
        $email = $_SESSION["admin_email"];
    } else {
        header("Location:../index.php");
}

After redirection, session variables are lost. I have tried a few tricks but it's still not working.

ITWitch
  • 1,729
  • 5
  • 20
  • 38
Rakesh Mishra
  • 358
  • 5
  • 17

3 Answers3

0

Take session_start(); and place at the top of all of your code. You essentially want it to be one of, if not, the first method to run.

I tend to create a file called lib.php which is called into the Header.php document. This lib file contains all object creation, certain functions, etc. The very first bit of code on the page is:

<?php
session_start();
//the rest of the code here
Harry Kitchener
  • 161
  • 1
  • 1
  • 11
0
You should start the session on all your php files like below code, else you can start session on common file (which file included on all files)

test1.php
<?php
session_start();
$_SESSION['admin_name'] = 'test';
$_SESSION['sbc_admin'] = "y";
$_SESSION['admin_email'] = 'test1';

header("Location:test2.php");
?>

test2.php
<?php
session_start();
print_r($_SESSION);
exit();
?>
GThamizh
  • 2,054
  • 3
  • 17
  • 19
0

Instead of using "session_start()" on all pages, you should have a PHP file that is included on all of your php pages. Just like a header or a config file.

You need to check if the session has started and to start the session if not. You can inspire from this answer to see how to check and start the session in PHP versions that appeared before and after 5.4: https://stackoverflow.com/a/18542272/1564840

Community
  • 1
  • 1
Pascut
  • 3,291
  • 6
  • 36
  • 64