PHP Pass variable to next page

后端 未结 8 2337
Happy的楠姐
Happy的楠姐 2020-11-21 06:40

It seems pretty simple but I can\'t find a good way to do it.

Say in the first page I create a variable

$myVariable = \"Some text\";
<
相关标签:
8条回答
  • 2020-11-21 07:14

    HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.

    Session:

    //On page 1
    $_SESSION['varname'] = $var_value;
    
    //On page 2
    $var_value = $_SESSION['varname'];
    

    Remember to run the session_start(); statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.

    Cookie:

    //One page 1
    $_COOKIE['varname'] = $var_value;
    
    //On page 2
    $var_value = $_COOKIE['varname'];
    

    The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.

    GET and POST

    You can add the variable in the link to the next page:

    <a href="page2.php?varname=<?php echo $var_value ?>">Page2</a>
    

    This will create a GET variable.

    Another way is to include a hidden field in a form that submits to page two:

    <form method="get" action="page2.php">
        <input type="hidden" name="varname" value="var_value">
        <input type="submit">
    </form>
    

    And then on page two:

    //Using GET
    $var_value = $_GET['varname'];
    
    //Using POST
    $var_value = $_POST['varname'];
    
    //Using GET, POST or COOKIE.
    $var_value = $_REQUEST['varname'];
    

    Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.

    The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.

    0 讨论(0)
  • 2020-11-21 07:16

    Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.

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