&reftitle.examples;

## Basic usage

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID.

Sessions follow a simple workflow. When a session is started, PHP will either retrieve an existing session using the ID passed (usually from a session cookie) or if no session is passed it will create a new session. PHP will populate the `$_SESSION` superglobal with any session data after the session has started. When PHP shuts down, it will automatically take the contents of the `$_SESSION` superglobal, serialize it, and send it for storage using the session save handler.

By default, PHP uses the internal `files` save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive.

Sessions can be started manually using the `session_start` function. If the session.auto_start directive is set to `1`, a session will automatically start on request startup.

Sessions normally shutdown automatically when PHP is finished executing a script, but can be manually shutdown using the `session_write_close` function.

### Registering a variable with `$_SESSION`.

    <?php
    session_start();
    if (!isset($_SESSION['count'])) {
      $_SESSION['count'] = 0;
    } else {
      $_SESSION['count']++;
    }
    ?>

### Unregistering a variable with `$_SESSION`.

    <?php
    session_start();
    unset($_SESSION['count']);
    ?>

Do NOT unset the whole `$_SESSION` with `unset($_SESSION)` as this will disable the registering of session variables through the `$_SESSION` superglobal.

You can't use references in session variables as there is no feasible way to restore a reference to another variable.

File based sessions (the default in PHP) lock the session file once a session is opened via `session_start` or implicitly via session.auto_start. Once locked, no other script can access the same session file until it has been closed by the first script terminating or calling `session_write_close`.

This is most likely to be an issue on Web sites that use AJAX heavily and have multiple concurrent requests. The easiest way to deal with it is to call `session_write_close` as soon as any required changes to the session have been made, preferably early in the script. Alternatively, a different session backend that does support concurrency could be used.

## Passing the Session ID

There are two methods to propagate a session id:

- Cookies

- URL parameter

The session module supports both methods. Cookies are optimal, but because they are not always available, we also provide an alternative way. The second method embeds the session id directly into URLs.

PHP is capable of transforming links transparently. If the run-time option `session.use_trans_sid` is enabled, relative URIs will be changed to contain the session id automatically.

The arg_separator.output &php.ini; directive allows to customize the argument separator. For full XHTML conformance, specify &amp; there.

Alternatively, you can use the constant `SID` which is defined if the session started. If the client did not send an appropriate session cookie, it has the form `session_name=session_id`. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using `SID`.

### Counting the number of hits of a single user

    <?php

    session_start();

    if (empty($_SESSION['count'])) {
       $_SESSION['count'] = 1;
    } else {
       $_SESSION['count']++;
    }
    ?>

    <p>
    Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
    </p>

    <p>
    To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click
    here</a>.
    </p>

The `htmlspecialchars` may be used when printing the `SID` in order to prevent XSS related attacks.

Printing the `SID`, like shown above, is not necessary if --enable-trans-sid was used to compile PHP.

Non-relative URLs are assumed to point to external sites and hence don't append the `SID`, as it would be a security risk to leak the `SID` to a different server.

## Custom Session Handlers

To implement database storage, or any other storage method, you will need to use `session_set_save_handler` to create a set of user-level storage functions. A session handlers may be created using the `SessionHandlerInterface` or extending PHP's internal handlers by inheriting from `SessionHandler`.

The callbacks specified in `session_set_save_handler` are methods called by PHP during the life-cycle of a session: `open`, `read`, `write` and `close` and for the housekeeping tasks: `destroy` for deleting a session and `gc` for periodic garbage collection.

Therefore, PHP always requires session save handlers. The default is usually the internal 'files' save handler. A custom save handler can be set using `session_set_save_handler`. Alternative internal save handlers are also provided by PHP extensions, such as `sqlite`, `memcache` and `memcached` and can be set with session.save_handler.

When the session starts, PHP will internally call the `open` handler followed by the `read` callback which should return an encoded string exactly as it was originally passed for storage. Once the `read` callback returns the encoded string, PHP will decode it and then populate the resulting array into the `$_SESSION` superglobal.

When PHP shuts down (or when `session_write_close` is called), PHP will internally encode the `$_SESSION` superglobal and pass this along with the session ID to the `write` callback. After the `write` callback has finished, PHP will internally invoke the `close` callback handler.

When a session is specifically destroyed, PHP will call the `destroy` handler with the session ID.

PHP will call the `gc` callback from time to time to expire any session records according to the set max lifetime of a session. This routine should delete all records from persistent storage which were last accessed longer than the `$lifetime`.