Session Management Without Cookies

A change that can be made to the default PHP session management is to encode the $PHPSESSID value as an attribute in a GET or POST method request and avoid the need to set a cookie.

A simple experiment that illustrates what happens when users disable cookies is to request the script shown in Example 8-2 from a browser that has cookie support turned off. When repeated requests are made, the counter doesn't increment, and the session duration remains at zero seconds. Because a cookie isn't sent from the browser, the variable $PHPSESSID is never set. The other side effect is that each time the page is requested, a session file is created in the /tmp directory. Many users configure their browsers to not accept cookies, and session-based applications won't work unless they are written to handle the missing cookie.

The session identifier that would have been sent as a cookie in this experiment can be transmitted in a GET or POST method request. While the session_start( ) function can use $PHPSESSID set by either a GET or POST method request, it is more practical to use the GET variable. Using the POST variable leads to the reload problem described in Chapter 6. Continuing the experiment, requests that don't contain the cookie can identify an existing session by setting an attribute in a GET method request with the name PHPSESSID and the value of the session ID. For example, an initial request can be made to Example 8-1 with the URL:


This creates a session and an associated file such as:


Subsequent requests can be made that include the PHPSESSID:


The response shows the counter set to 1 and the correct session duration. Repeated requests to this URL behave as expected: the counter increments, and the calculated duration increases.

If you write session-based applications to use the URL to identify sessions, the application doesn't fail for users who don't allow cookies. Applications can use a test cookie to see if cookies are supported by the browser or just not use cookies at all.

When register_globals is enabled, and both a cookie and GET or POST are used to set the $PHPSESSID, the cookie wins. A GET or POST attribute value is overwritten by the value associated with the cookie because of the default order in which PHP initializes those variables.

The safe way to read cookies and GET and POST attributes that have name conflicts is to use the $HTTP_COOKIE_VARS, $HTTP_GET_VARS, and $HTTP_POST_VARS arrays.

Another advantage of avoiding cookies is that some browsers, such as Netscape and Internet Explorer, share cookies across all instances of the program running for a particular user on the same machine. This behavior prevents a user from having multiple sessions with a web database application.