With the basics of sessions out of the way, let's examine exactly how sessions work by customizing how sessions are handled internally. By default, PHP provides three internal methods of storing session data specified by
session.save_handler: the internal PHP session file format (specified by
php), within an SQLite database (specified by
sqlite) and the WDDX packet format (specified by
wddx).
When it comes to session handling, perhaps the most useful capability of PHP does not lie in the internal session handlers. Rather, PHP provides the means to completely customize session handling by allowing you, the developer, to specify your own PHP functions that will be used to save and restore session data as necessary.
When using user-defined session handlers, six individual functions must be defined for sessions to work properly, as described next:
-
Starting (opening) the session.
-
Reading any existing session data from storage.
-
Writing current session data to storage.
-
Ending (closing) the current session.
-
Cleaning up any unused or invalid session data from storage.
-
The six functions each have specific parameters and return values, as shown next:
-
Opening Accepts two parameters, $save_path (the path to write any session-related files) and $session_name (the actual session name). Both of these parameters are taken from session.save_path and session.name configuration directives, respectively. This function returns a Boolean indicating whether the session was initialized successfully.
-
Reading Function Accepts one parameter, $id (the session ID of the current session), and must return either the session data or an empty string if no data is available.
-
Writing Function Accepts two parameters, $id (again, the session ID of the current session) and $sess_data (the serialized session data). This function returns a Boolean value indicating whether the session data was stored successfully.
-
Closing Function This function takes no parameters and returns a Boolean indicating success.
-
Cleaning Function This function takes a single parameter (the maximum lifetime of a session as specified by the session.gc_maxlifetime directive) and returns a Boolean indicating whether the function call was successful.
-
Destroying Function This function takes a single parameter (the session ID of the current session) and returns a Boolean indicating whether the function was destroyed successfully.
To use a user-defined session handler, each function must be created and then registered using the session_set_save_handler() function. The syntax of this function is as follows:
session_set_save_handler($open, $close, $read,
$write, $destroy, $gc)
Each of the six parameters represents the string name of the associated user-defined function. This function returns a Boolean indicating whether the custom session handler was installed successfully.