Sessions and Cookies - LEARN PHP IN A DAY: The Ultimate Crash Course to Learning the Basics of PHP in No Time (2015)

LEARN PHP IN A DAY: The Ultimate Crash Course to Learning the Basics of PHP in No Time (2015)

Chapter 8. Sessions and Cookies

Introduction

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Sessions

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$_SESSIONsuperglobal 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 bysession.save_handler. This saves session data on the server at the location specified by thesession.save_path configuration directive.

Sessions can be started manually using thesession_start()function. If thesession.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 thesession_write_close() function.

Caution

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

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. Unless you are usingPHP 4.2.0 or later, you need to enable it manually when building PHP. Under Unix, pass--enable-trans-sidto configure. If this build option and the run-time optionsession.use_trans_sid are enabled, relative URIs will be changed to contain the session id automatically.

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 formsession_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.

Custom Session Handlers

To implement database storage, or any other storage method, you will need to usesession_set_save_handler()to create a set of user-level storage functions. As of PHP 5.4.0 you may create session handlers using theSessionHandlerInterfaceor extend internal PHP handlers by inheriting fromSessionHandler.

The callbacks specified insession_set_save_handler()are methods called by PHP during the life-cycle of a session:open, read, write and closeand for the housekeeping tasks:destroyfor deleting a session andgc 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 usingsession_set_save_handler(). Alternative internal save handlers are also provided by PHP extensions, such assqlite, memcache and memcachedand can be set withsession.save_handler.

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

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

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

PHP will call thegccallback 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.

Cookies

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.

Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add [] to the cookie name.

Depending on register_globals, regular PHP variables can be created from cookies. However it's not recommended to rely on them as this feature is often turned off for the sake of security.

For more details, including notes on browser bugs, see the setcookie() and setrawcookie() function.

A cookie is created with the setcookie() function.

Creating and retrieving cookies with PHP

The following example creates a cookie named "user" with the value "John Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer).

We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:

The setcookie() function must appear BEFORE the <html> tag.

Modifying a cookie using PHP

To modify a cookie, just set (again) the cookie using the setcookie() function:

Deleting a cookie using PHP

To delete a cookie, use the setcookie() function with an expiration date in the past:

Check if Cookies are enabled using PHP

The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:

Conclusion

In this chapter we covered creating and destroying Cookies and Sessions in PHP