Maintaining information between accesses using Sessions

HTTP is a stateless protocol, each request to the web server is processed without any knowledge of past or future requests. Cookies have traditionally been the standard method of tracking users or maintaining data, but they are limited by size, the number allowed, and they are stored on the client. We need a method to keep track of a user and their choices between visits to your website, while maintaining that information on our server vice the user's client.

Sessions and PHP

PHP allows us to track each visitor via a unique session ID which can be used to correlate data between connections. This id is a random string sent to the user when a session is created and is stored within the user's browser in a cookie (by default called PHPSESSID). This cookie can be seen below in the image (from Chrome's developer tools).

session cookie in browser

On the server side, the system stores this Session ID and an associated array of information concerning the client that your PHP scripts can use, in a file or in a database

Creating, using, and deleting SESSIONs

To use sessions you must start your PHP script with:

session_start();

This line of code should come before any output is produced by the script!! The session_start() function either creates a new session, if one does not exist, or it continues an existing session.

After the sessions has begun, you may access and use the $_SESSION global array and any changes to this array will survive between web page accesses! To set a value, treat this variable like you would any array.

$_SESSION['myvariable'] = 'myvalue';

Setting a session variable by modifying the $_SESSION array stores that information in a file or database (depending on the server settings) and you will now be able to access this information from any script, as long as the session is valid.i

Note: If you wanted to quickly output the entire contents of $_SESSION for debugging purposes, you can print out any associative array in a nice format with print_r() surrounded by <pre> tags.

>
<pre><?php print_r($_SESSION); ?></pre>

When working with session values, it is often useful to test whether a particular session variable exists. The easiest way to check to see if a variable exists is with isset().

if (isset($_SESSION['myvariable']) {
  echo $_SESSION['myvariable'];
}

If you wish to delete a session variable, you should unset it (just like you can any variable in PHP):

unset($_SESSION['myvariable']);

If you want to remove the entire contents of the SESSION, you can destroy it.

session_destroy();

Retrieving SESSION information for continuity between browsers

Since your users might connect from different browsers on different computers, if you want to preserve some session information (e.g. a shopping cart started on one computer and continued on another), it may become necessary to store their session information in a file under your control so that when they log on you can recreate their session.

The session_id can be retrieved from your PHP script after session_start() has been run via:

$myid = session_id();
The session data can be converted to a string with:

$mysession = session_encode();
And this string can be converted back to the $_SESSION array with:

session_decode($mysession);
With only the functions above, we can encode and decode the SESSION into and from a string. This string can be easily stored within a file. Imagine this scenario: a user connects to a website and logs on. The session information is then retrieved and restored to their $_SESSION variable. As they move through the website, any changes in the SESSION can then be captured and written back so every transaction they have with your website, from anywhere, is seamless.

There are a few big differences between cookies and sessions:

Remember: sessions work by just storing a single cookie on the browser.

Debugging

You are expected to debug your code constantly, the best way to do that with PHP is to review the error log from the Apache web server. To review the logs:

  1. Log onto the web server (midn.cs.usna.edu) via ssh

    ssh midn.cs.usna.edu
  2. Tail (a command that allows you to see the last few lines of a file, or continuously watch the file for new additions with the -f flag) the error log via:

    tail -f /var/log/apache2/error.log
    It may be useful, to just focus on your own errors, and that can be done by piping the results of tail through grep to search for your mAlpha

    tail -f /var/log/apache2/error.log | grep mAlpha
  3. If any of the errors are confusing, take a look at the error guide located within the resources page of this class, or online. As with any language, it is recommended that you work on the first error that appeared, then try running your code again as errros may be linked to each other.
  4. Additionally, you can retrieve your web page via the command line to see exactly what was returned. Curl is an excellent utility for this, and the -v (verbose option) will show you the back-and-forth traffic with the web server.

    curl -v http://midn.cs.usna.edu/~mAlpha/IT350/test.php
  5. In Chrome, you can press ctrl-shift-j to toggle the debugger, this is useful as you can see exactly what was received by the browser.
Please note: When something is not working (internal server error), check the error log file. You should be able to debug on your own, before asking the instructor for help if needed.

Problems

Sessions are a valuable tool in creating websites with content that follows a user between visits, lets practice a bit.

  1. Create a PHP script that remembers the last time you visited the page and prints it out. If it is your first visit, it should welcome you to the site. Take a look at the date() function.