phpphp-includedynamic-content

How do I pass a dynamic PHP variable from one page to another?


I am creating 2 webpages. The first one will show a list of items. 2nd web page, I want to create a general one so that when the user clicks on an item depending upon the chosen one, 2nd page will be modified as per item. I just want to pass a string variable from which I can obtain rest of the the things from database. Just like an e-commerce website.


Solution

  • There are a couple of ways to achieve what you want.

    Some examples:

    Using GET:

    You can use a link to pass a variable to the next page.

    Page 1:

    <a href="yourpage2.php?variable=<?php echo $value; ?>">Page 2</a>
    

    Page 2:

    if(isset($_GET['variable'])) {
        $new_variable = $_GET['variable'];
    }
    

    Using POST:

    Page 1:

    <form method="POST" action="yourpage2.php">
        <input type="hidden" name="variable" value="<?php echo $value; ?>">
        <input type="submit" value = "Next Page">
    </form>
    

    Page 2:

    if(isset($_POST['variable'])) {
       $new_variable = $_POST['variable'];
    }
    

    Using COOKIE:

    Page1:

    $_COOKIE['variable'] = $value;
    

    Page 2:

    $new_variable = $_COOKIE['varname'];
    

    When using cookies, the variable's value is stored on the client side, opposite of sessions, where the value is stored on the server side.

    Using SESSION:

    Page 1:

    $_SESSION['variable'] = $value;
    

    Page 2:

    $new_variable = $_SESSION['variable'];
    

    Notice: When using SESSIONS, do not forget to include/write session_start(); in the start of your page right after your <?php tag on BOTH of your pages.