05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Session basics<br />

To enable sessions for a page, call session_start() before any of the document has<br />

been generated:<br />

<br />

<br />

...<br />

<br />

This assigns a new session ID if it has to, possibly creating a cookie to be sent to the<br />

browser, and loads any persistent variables from the store.<br />

If you have registered objects, the class definitions for those objects must be loaded<br />

before the call to session_start(). See Chapter 6 for discussion and an example.<br />

You can register a variable with the session by passing the name of the variable to<br />

session_register(). For example, here is a basic hit counter:<br />

<br />

This page has been viewed times.<br />

The session_start() function loads registered variables into the associative array<br />

$HTTP_SESSION_VARS. The keys are the variables’ names (e.g., $HTTP_SESSION_<br />

VARS['hits']). If register_globals is enabled in the php.ini file, the variables are also<br />

set directly. Because the array and the variable both reference the same value, setting<br />

the value of one also changes the value of the other.<br />

You can unregister a variable from a session, which removes it from the data store,<br />

by calling session_unregister(). The session_is_registered() function returns true<br />

if the given variable is registered. If you’re curious, the session_id() function returns<br />

the current session ID.<br />

To end a session, call session_destroy(). This removes the data store for the current<br />

session, but it doesn’t remove the cookie from the browser cache. This means that,<br />

on subsequent visits to sessions-enabled pages, the user will have the same session<br />

ID she had before the call to session_destroy(), but none of the data.<br />

Example 7-13 shows the first code block from Example 7-11 rewritten to use sessions<br />

instead of manually setting cookies.<br />

Example 7-13. Setting preferences with sessions<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!