Because your program canât tell what variables were set in other programsâor even what values the same program set the previous time it ranâyouâll sometimes want to track what your users are doing from one web page to another. You can do this by setting hidden fields in a form, as seen in ChapterÂ 10, and checking the value of the fields after the form is submitted, but PHP provides a much more powerful and simpler solution in the form of sessions. These are groups of variables that are stored on the server but relate only to the current user. To ensure that the right variables are applied to the right users, a cookie is saved in their web browsers to uniquely identify them.
This cookie has meaning only to the web server and cannot be used
to ascertain any information about a user. You might ask about those
users who have their cookies turned off. Well, thatâs not a problem
since PHP 4.2.0, because it will identify when this is the case and
place a cookie token in the
portion of each URL request instead. Either way, sessions provide a
solid way of keeping track of your users.
Starting a Session
Starting a session requires calling the PHP function
session_start before any HTML has been
output, similarly to how cookies are sent during header exchanges.
Then, to begin saving session variables, you just assign them as part
$_SESSION array, like
$_SESSION['variable'] = $value;
They can then be read back just as easily in later program runs, like this: ...