How do I share a PHP variable between multiple pages?

后端 未结 5 685
离开以前
离开以前 2020-12-20 09:36

The idea/goal:

I have a username and password inside a text file on my computer. The form on the index page allows the user to sign in with their us

相关标签:
5条回答
  • 2020-12-20 09:59

    You can start a session and put the form values into the $_SESSION variable, which will be available on all pages.

    // On the page where your form is submitted:
    session_start();
    $_SESSION['name'] = $_POST['name'];
    
    // On the page where the user is redirected:
    session_start();
    echo $_SESSION['name'];
    

    Note that in reality you would probably want to include some form validation too!

    0 讨论(0)
  • 2020-12-20 10:01
    1. Start a php session on each page right after the opening php tag:

      session_start();

    After you determine that the name and password work, and before you do the redirect, add this line:

    $_SESSION['name'] = $name;

    On any subsequent pages, just echo something like this:

    echo "Welcome ".$_SESSION['name'];
    
    0 讨论(0)
  • 2020-12-20 10:06

    Use session variables

    set:

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

    get:

    session_start();
    $username = $_SESSION['username'];
    
    0 讨论(0)
  • 2020-12-20 10:07

    I agree with @Clément Malet & @Hammerstein. Sessions and/or cookies.

    <?php 
        // always need this
        session_start();
    
        // set the value
        $_SESSION['username'] = 'Person';
    ?>
    
    <?php
        //get session data
        echo $_SESSION['username'];
    
       // output: Person
    ?>
    
    0 讨论(0)
  • 2020-12-20 10:25

    Use $_SESSION -!

    session_start();
    $_SESSION['username'] = $_POST['username'];
    

    You of course want to filter/sanitize/validate your $_POST data, but that is outside of the scope of this question...

    As long as you call session_start(); before you use $_SESSION - the values in the $_SESSION array will persist across pages until the user closes the browser.

    If you want to end the session before that, like in a logout button --- use session_destroy()

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