How Can Variables Be Carried across Multiple PHP Pages (Not Just Immediate Subsequent Pages)?

Problem scenario
You want to pass variables from user input and have them carry across multiple pages.  You may or may not want the immediate subsequent page to use the variables.  You want pages (.php files) after several clicks of navigation (two pages or more) to employ the variables that were read in or calculated via PHP pages.

You are using session_set() and/or session_start() but they are not working.  Your $_SESSION['variablename'] usage is not working as you expect.  What do you do to have global variables so you can take in user input from one page and have pages two pages away use those variables?

Solution
Use session_start() above any HTML code on the page after the "Submit" button was clicked.  That is, on a page that has the $_POST['varname'] available, use the session_start() PHP function before any HTML code.  Do not use session_set() for a modern version of PHP.  Here are three pages below that can work as an illustration.  To use them, you'll put them all in the same directory.  The first one will read in user input.  The second page acts as an intermediate page.  The third page (arrived to by clicking a button on the second page), has access to the global variables which are the user input.

1.  one.php should have the following content:

<html>
<body>
<h2> Welcome to page 1.  Enter your credentials here.</h2>
<form action="two.php" method="post">
UserName: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit">
</form>

</body>
</html>

2.  two.php should have the following content:

<?php
   session_start();
   $_SESSION['username'] = $_POST['username'];
   $_SESSION['password'] = $_POST['password'];
?>
<html>
<body>
<h2> Welcome to page 2.  Click submit to proceed to the third page.  </h2>
<form action="three.php" method="post">
<input type="submit">
</form>

</body>
</html>

3.  three.php should have the following content:

<?php
   session_start();
   echo "The username you entered on the first page was ";
   echo $_SESSION['username'];
   echo ".";
   echo "\n";
   echo "This proves the variable is global.";
   $var1 = $_SESSION['username'];  //This is a suggestion for PHP coding.
?>

4.  Go to http://x.x.x.x/one.php and enter any username and password you like.  Make sure the username is not blank.  Click "Submit query."  Click "Submit query" again.

Leave a comment

Your email address will not be published. Required fields are marked *