Skip to content Skip to sidebar Skip to footer

Pass Variable To More Than One Page

I'm able to pass a variable from a link on my first page to the 2nd page, but i'm having a hard time passing that variable into the third page. How can i pass the variable to the t

Solution 1:

To pass a variable along from one page to another you can choose from multiple options:

  • Sessions
  • Cookies
  • Storage (File or Database)

Sessions

The first page:

<?php// Prepare to use sessions (This should be at the top of your page)
session_start();

if (!isset($_SESSION['test']) && isset($_GET['test'])) {
    $_SESSION['test'] = $_GET['test'];
    header("Location: secondpage.php");
    exit;
}

The second page:

<?php
session_start();

// Output session
var_dump($_SESSION['test']);

Cookies

First page:

<?phpif (isset($_GET['test'])) {
    setcookie('test', $_GET['test'], time() + (86400 * 30), "/");
}

Second page: "; echo "Value is: " . $_COOKIE['test']; }

Files and Databases

This is too big a subject to discuss in one answer. However, there are tons of tutiroals that can learn you all you need to know about PHP and MySQL.

Example

First page:

<ahref="page_two.php?page=two">Go</a>

Second page:

<?php
session_start();
if (isset($_GET['page'])) {
   $_SESSION['page'] = $_GET['page'];
}
header("Location: page_three.php");
exit;
?>

Third page:

<?php
session_start();
// Will echo twoecho$_SESSION['page'];
?>

Resources

Solution 2:

You have two main options:

  1. you can keep linking the pages with url parameters <a href="SecondPage.php?Page=Two">Go to Page Two</a> <a href="ThirdPage.php?Page=<?php echo $_GET["Page"] ?>">Go to Page Three</a>

This solutions is quite inconvenient if you want to keep the "page" value for a long term

  1. The best solution as user1234 said is to store the value in the session.

if your first page MUST be html and you can't store it at begining you can do in any of your php pages

$_SESSION['Page'] = $_GET["Page"];

Post a Comment for "Pass Variable To More Than One Page"