How do I continue a session from one page to another with PHP

后端 未结 8 1566
夕颜
夕颜 2020-11-27 07:34

Ok I set up a session... but now how do I make it work on my other pages?

I tried doing

@session_start();

if(isset($_SESSION[\'$userName\'])) {

 ec         


        
相关标签:
8条回答
  • 2020-11-27 07:51

    first page (hello1.php) - Storing Session

    $userName = "Nick";
    session_start();
    $_SESSION['username'] = $userName;
    

    second page (hello2.php) - Output Session

    session_start();
    $userName = $_SESSION['username'];
    echo "$userName";
    

    Output: Nick

    0 讨论(0)
  • 2020-11-27 07:55

    Make sure session_start() is at the top of every page you wish to use sessions on. Then you can refer to session variables just like in your example.

    0 讨论(0)
  • 2020-11-27 07:57
    1. Create a login page, the user must not login without correct id and passowrd.
    2. After logging in the user comes to the home, here user can logout and goes back to the login page

    NOTE: User must not access home page without going through login page.

    0 讨论(0)
  • 2020-11-27 08:02

    Be aware of case sensitivity in the $_session name variables.

    Therefore $_SESSION['userName'] different with $_SESSION['username'].

    0 讨论(0)
  • 2020-11-27 08:06

    On the first page (test1.php),

    <?php
    session_start();
    
    $_SESSION['userName'] = 'This is Ravi';
    
    ?>
    

    On the second page (test2.php),

    <?php
    session_start();
    if(isset($_SESSION['userName'])) {
    echo "Your session is running " . $_SESSION['userName'];
    }
    
    ?>
    
    0 讨论(0)
  • 2020-11-27 08:09

    If your PHP setup is clear (session writing ok) and cookie normally sent to browser (and preserved), you should be able to do something like this

    On first page :

    session_start();
    $_SESSION['userName'] = 'Root';
    

    On a second page :

    session_start();
    if(isset($_SESSION['userName'])) {
      echo "Your session is running " . $_SESSION['userName'];
    }
    

    Be careful session_start() must be called before any output is sent, so if you had to use the @ for session_start it can hide warnings.

    As these are warnings, if given example doesn't work try to add this before calling session_start :

    error_reporting(E_ALL);
    
    0 讨论(0)
提交回复
热议问题