Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
Python and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Lua, etc
Passing variable between PHP pages - hidden fields, cookies and sessions

Variables 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

And that colour is used within the HTML:

  <body bgcolor="<?= $mycolour ?>">


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:


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:


When we've completely finished with the session (final page ONLY!!):


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.
(written 2013-04-26, updated 2013-04-27)

Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
H112 - PHP - Further Web Page and Network Handling
  [4483] Moving from mysql to mysqli - simple worked example - (2015-05-03)
  [3918] Multiple page web applications - maintaining state - PHP - (2012-11-10)
  [3568] Telling which ServerAlias your visitor used - useful during merging domains - (2012-01-04)
  [3540] Easy session example in PHP - keeping each customers data apart - (2011-12-06)
  [3432] 3 digit HTTP status codes - what are they, which are most common, which should be a concern? - (2011-09-11)
  [3036] Sending out an email containing HTML from within a PHP page - (2010-11-07)
  [2918] Downloading a report from the web for further local analysis - (2010-08-13)
  [2729] Uploading a document or image to its own URL via a browser - (2010-04-18)
  [2679] How to build a test harness into your PHP - (2010-03-16)
  [2632] Shipping a test harness with your class in PHP - (2010-02-12)
  [1549] http, https and ajp - comparison and choice - (2008-02-22)
  [1518] Downloading data for use in Excel (from PHP / MySQL) - (2008-01-25)
  [1515] Keeping staff up to date on hotel room status - (2008-01-22)
  [1505] Script to present commonly used images - PHP - (2008-01-13)
  [1496] PHP / Web 2 logging - (2008-01-06)
  [1495] Single login and single threaded models - Java and PHP - (2008-01-04)
  [1485] Copyright and theft of images, bandwidth and members. - (2007-12-26)
  [1379] Simple page password protection - PHP - (2007-10-04)
  [1355] .php or .html extension? Morally Static Pages - (2007-09-17)
  [1210] PHP header() function - uses and new restrictions - (2007-05-30)
  [1187] Updating a page strictly every minute (PHP, Perl) - (2007-05-14)
  [1183] Improving searches - from OR to AND? - (2007-05-11)
  [1114] PHP Image upload script - (2007-03-21)
  [1009] Passing GET parameters through Apache mod_rewrite - (2006-12-27)
  [936] Global, Superglobal, Session variables - scope and persistance in PHP - (2006-11-21)
  [904] Of course I'll tell you by email - (2006-10-25)
  [847] Image maps for navigation - a straightforward example - (2006-08-28)
  [789] Hot answers in PHP - (2006-07-02)
  [767] Finding the language preference of a web site visitor - (2006-06-18)
  [675] Adding PHP tags to an old cgi program - (2006-04-08)
  [603] PHP - setting sort order with an associative array - (2006-02-13)
  [565] Using PHP to output images, XML, Style sheets, etc - (2006-01-15)
  [542] Morning image, afternoon image - (2005-12-26)
  [537] Daily Image Santafied - (2005-12-22)
  [484] Setting the file name for a downloaded document - (2005-11-03)
  [451] Accessing a page via POST from within a PHP script - (2005-09-26)
  [443] Server side scripting of styles to suit the browser - (2005-09-12)
  [425] Caching an XML feed - (2005-08-26)
  [410] Reading a news or blog feed (RSS) in your PHP page - (2005-08-12)
  [376] What brings people to my web site? - (2005-07-13)
  [372] Time calculation in PHP - (2005-07-08)
  [356] Sudoku helper or sudoku cheat - (2005-06-23)
  [345] Spotting a denial of service attack - (2005-06-12)
  [314] What language is this written in? - (2005-05-17)
  [220] When to use Frames - (2005-02-19)

H301 - PHP - Sticky fields and session
  [3820] PHP sessions - a best practice teaching example - (2012-07-27)
  [2738] What is all this SESSION stuff about? (PHP) - (2010-04-25)
  [2416] Automating access to a page obscured behind a holding page - (2009-09-23)
  [1911] Remember Me - PHP - (2008-11-28)
  [1766] Diagrams to show you how - Tomcat, Java, PHP - (2008-08-22)
  [1739] Bath, Snake or Nag? - (2008-08-06)

Back to
Even early on, separate out your program from your HTML!
Previous and next
Horse's mouth home
Forward to
Setting up strings in PHP
Some other Articles
A comment on comments in PHP
Learning about Object Orientation in PHP - a new set of examples
Splitting the difference with PHP
Setting up strings in PHP
Passing variable between PHP pages - hidden fields, cookies and sessions
Even early on, separate out your program from your HTML!
Arrays in PHP - contain different and even mixed data types
The woman, the television, the bullock and Darlington
MVC and Frameworks - a lesson from first principles in PHP
Handling requests to a forum - the background process
4759 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 at 50 posts per page

This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2019: 404 The Spa • Melksham, Wiltshire • United Kingdom • SN12 6QL
PH: 01225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/4070_Pas ... sions.html • PAGE BUILT: Sat May 27 16:49:10 2017 • BUILD SYSTEM: WomanWithCat