Passing variable between PHP pages - hidden fields, cookies and sessions
Archive - Originally posted on "The Horse's Mouth" - 2013-04-26 19:59:26 - Graham EllisVariables within a program are lost when the program exits ... unless the program takes some sort of action to save them. And if it does, you've then got to have another program pick them up to use them somehow.
Web applications in PHP are a series of short-running programs. A program is run each time you submit a request to the server, and that running is complete once the response has been sent out. So how do you link this series of short-running programs?
You could simply save the data to the disc when one step of a series runs, and read it in when the next step runs. But that's not a complete answer, because many users will be running the same series of programs at the same time, and if your program were to simply read the latest data, you would have a leakage of one user's inputs - perhaps highly confidential data - to the next user to come along. You need the user's help, via his browser.
Solution number 1 is to send out a unique element within the URL of the next page, or a hidden field. Unique URLs get us into the realm of Apache routers, and we dont usually want to go there. But a hidden field is a good solution, provided that we know that the user will move seemlessly onto the next page in our series and won't go off for a tour the web's byways before carrying on. The hidden field (or unique URL) could simply be the data that's to be passed on to the next page, but if that data's large, or confidential in any way, you'll want to store the real data in a file on the server and just pass out a key to that file - probably the file name, which I'm going to suggest you generate with the uniqid function.
Solution number 2 is similar - except that you use a cookie in place of the hidden field. Just like a hidden field, a cookie is a name - value pair. But - unlike a hidden field - it's retained by the browser and returned to the server on each subsequent page and not just the immediate following one. Thus a cookie empowers the browser to say to the server "It's me" and "It's me again" at each subsequent request. Cookies are usually domain based - in other words, they'll be passed back to any subsequent page called up on the same server. They can be more limited - e.g. directory based. By default, the browser remembers them until it's shut down, but by specifying a time to live, the web application programmer can ask the browser to store them for days or even years.
From the course just concluded, there's a new example of setting a cookie to remember a user's favourite colour - [here]. You can run the code [here].
First, the code checks if there's a valid cookie set already:
if (isset($_COOKIE["favcolour"])) {
if (in_array($_COOKIE["favcolour"],$colours)) {
$mycolour = $_COOKIE["favcolour"];
then in checks if there's a user input request to set a (new) favourite colour:
if (isset($_REQUEST["ilikes"])) {
if (in_array($_REQUEST["ilikes"],$colours)) {
$mycolour = $_REQUEST["ilikes"];
If there is indeed a new colour to be set, a fresh cookie is sent:
$until = time() + 3600; // Live for an hour
setcookie("favcolour",$mycolour,$until);
And that colour is used within the HTML:
<body bgcolor="<?= $mycolour ?>">
Samples:

Just above, I hinted that you'll often want to store a whole lot of data, and pass that data on from one page to the next. And that's messy, clunky, inefficient and insecure if you try to store all the data in cookies. You want to use a unique key as the cookie value, and save and restore data off the server disc. As that's a common requirement, there are functions to help you. session_start called at the top of every page that uses the session ("shopping cart") loads the user's previous data into a superglobal array called $_SESSION and that is automatically resaved at the end of each page being processed. The session code also looks after generating the uniqid, and sending the cookie if necessary. Full code [here]. Try it out [here].
Here's some of the code ...
Start the session:
session_start();
See if there's a "current" variable in the session - if not, initialise it to zero:
if (! isset($_SESSION["current"])) { $_SESSION["current"] = 0; }
Add an incoming value from the user to an array we've called "cart" within the session:
array_push($_SESSION["cart"],$_REQUEST["yummy"]);
When we've completely finished with the session (final page ONLY!!):
session_destroy();
We introduce cookies and sessions on our Learning to program in PHP and PHP Programming courses. And we cover them in much more detail on our more advanced PHP Techniques Workshop.