HTTP cookies help track user sessions. For example, the first time a visitor arrives at an online store a session is created. The script then uses the session identifier any time the site needs to store information about the user, such as adding a purchase to an online order. Every request the browser makes to the server then includes the session-identifier cookie, which allows the application to identify the user associated with each request.
You can configure cookies to expire at any specified date and time or after a certain duration. Use the mktime function to generate an expiration based on a specific date or the time function to get the current date and time.
To generate a unique session ID, use the uniqid function. The result will be unique so long as no two IDs are generated at the same microsecond. The uniqid function can optionally be passed the user's IP address to remove the chance of two users getting the same session identifier.
The script starts by checking for an existing session cookie. All cookies are stored in the $HTTP_COOKIE_VARS associative array. Only when there is no existing session identifier will a new one be generated.
The example in Listing 7 provides a session that lasts until the user exits the browser. Listing 8 generates a session cookie that will last until January 1, 2000.Listing 8: Generating a session ID with a specific expiration date