How do I pass data between pages in PHP?

PHP is stateless unless you save things in session (which isn’t secure right?)

You would need to make page2.php read all the values from page1.php and store them either in a server side state (session) or a client state (cookies or maybe hidden fields in the form)

If you want any of this secure or a secret, then you have to consider all of that as well. Nothing I explained is secret or secure in any way.

EDIT: here is an example of page1.php that sends the values of page1.php to page2.php as get parameters. You can do this with hidden fields, cookies or sessions as well.

What is important to remember is that page2.php is totally unaware of page1.php, and can’t get to the values like you could it forms programming. Each page starts and ends it’s life by the time you see a full web page, so you have to use some extra tricks to keep values. Those tricks are sessions, cookies, form posts, or gets.

<html>
<head>
<title>Page 1</title>
</head>
<body>
<?php
//set defaults assuming the worst
$total = 0;
$one =0;
$two=0;

//verify we have that value in $__POST
if (isset($_POST['submit']))
{
    $submit = $_POST['submit'];
    //If it is true, try some math
    if($submit == "sub-total")
        {
            if (isset($_POST['one']))
            {   
                $one = $_POST['one'];
                //Add checks to see if your values are numbers
                if ( ! is_numeric($one)) { $one = 0;}
            }

            if (isset($_POST['two']))
            {
                $two = $_POST['two'];
                if ( ! is_numeric($two)) { $two = 0;}
            }
            $total = $one + $two;
            echo " Your Price is \$ " .number_format ($total, 2, '.', ','). "<BR>";
        }
    if($submit == "submit" )
    {
        //go to page two, with the total from page1.php passed as a $__GET value
        header("Location: page2.php?total=".$total);
    }
}
?>
    <form method="post" action="page1.php?submit=true">
        <input type="text" name="one" id="one" value="<?=$one?>"/>
        <input type="text" name="two" id="two"  value="<?=$two?>"/>
        <input type="submit" name="submit" value="sub-total" />
        <input type="submit" name="submit" value="submit" />
    </form>
</body>
</html>

Leave a Comment