Introduction to Maintaining the State of Applications with PHP Sessions

In PHP, session management is used to help web applications maintain their state across several HTTP requests when needed. In this first part of a series, you will learn the basics of the PHP built-in session mechanism, as well as some of its many useful functions.


Due to the fast evolution of Web programming, the stateless nature of the HTTP protocol brought many problems to certain Web applications that required maintaining their state across several HTTP requests. This demanded a rapid development of several mechanisms aimed at tackling this issue through diverse methods.

Particularly, in the universe of PHP programming, session management emerged as a direct response to the above mentioned problem, and currently this mechanism is being used by PHP developers worldwide, in cases where a Web application needs to keep track of its “state” during the occurrence of different HTTP requests.

Whether you’re a beginner developer or an experienced PHP programmer, it’s quite probable you’ve already used some of the built-in functions included within the PHP session management module, when constructing user authentication systems, shopping carts or web-based email applications, to name a few illustrative cases.

Indeed, PHP sessions are very simple to use. They hide all the complexities inherent to where and how to store session data, and provide developers with a transparent mechanism for managing information that must persist or keep state even if different HTTP requests are triggered across the same Web application.

Since PHP sessions are one of those things that sooner or later you must learn as a PHP developer, in this article I shall provide an overview of them. I will begin with the basics of how to use them, highlighting their strong points and weaknesses, and finally explore some of their most advanced concepts. By the end of this series, you should have all the knowledge that you need to start using the most common PHP session management functions, so you can use them during the development of your own applications.

With the preliminaries out of the way, it’s time to move on and start out exploring the features of the session management mechanism in PHP. Let’s get going!

{mospagebreak title=Working with persistent data: the basics of session management}

The first step involved in the use of PHP sessions is naturally indicating to the PHP interpreter that some kind of persistent data must be stored in the course of a session, in such a way that this data will maintain its value across different HTTP requests. How is this done? Basically, when a session is created, these are the key operations performed by the PHP session management mechanism:

  • A cryptographic session identifier is created (known as the session ID), which is saved in the client in a cookie (this is the default behavior), or propagated by the URL as part of the query string (also known as URL propagation).

  • Session data is stored on the server in text files (the default directory for storing session data is /tmp), but this behavior can be easily changed to save session data in shared memory or even database tables.

  • The corresponding session ID is associated with saved session data, in this way providing a method for tying a particular user to this data.

Right, these are at least the basic operations performed internally by the PHP session module, when a new session is started. As you saw, they’re very comprehensive.

Before I show you some illustrative hands-on examples, let me explain how session IDs are propagated across different HTTP requests. First off, the PHP session module uses cookies as the default way to propagate session IDs between different pages. Additionally, IDs can be propagated by GET/POST requests, by appending to each URL the name of the session together with the corresponding session ID. The following example shows how to pass a session ID between pages:

<a href=”sesionscript.php?<?php echo ‘PHPSESSID=’.session_id()?
>”>Click here</a>

In addition, PHP offers the global constant SID, which can be used to propagate session IDs within the URL, as follows:

<a href=”sesionscript.php?<?php echo SID?>”>Click here</a>

Finally, it’s possible to propagate session IDs by using the powerful “URL rewrite” feature, which automatically parses relative URLs and includes the session ID as part of the querystring. To enable this handy feature, PHP must be configured with the “—enable-trans-id—option and then recompiled.

Having explained the different methods for propagating session IDs, here’s a simple script that creates (or resumes) a session, and registers some data in the superglobal $_SESSION array:

// register session variables
// display session variables
echo ‘My first name is ‘.$_SESSION[‘firstname’].’ and my last
name is ‘.$_SESSION[‘lastname’];

As you can see, the above script is very simple. It first creates a new session or resumes an existing one by the “session_start()” function, and then stores my first and last names respectively as session data. As I explained before, if there is not a previous session, PHP will first generate a pseudo random session ID, then create a session file on the server using that ID, and save the serialized data in this file. In addition, the corresponding session ID will be stored in the client by using a cookie.

Of course, this sequence is the default behavior of the session module. However, as you’ll see later on, this process can be entirely changed, in order to utilize either shared memory or database tables for storing session data.

Now, I’ll continue exploring the PHP session module, by using some other interesting functions. Have a look at the following example, which uses the “session_id()” function:

echo ‘Old session ID :’.session_id();
// generate a new session ID
echo ‘New session ID: ‘.session_id();

In this case, after running the above script, these are the values outputted to the browser:

Old session ID :e0c9904e70f283343f5aba1bad09aa69
New session ID: b0169350cd35566c47ba83c6ec1d6f82

As shown above, the “session_id()” function comes in very handy either for retrieving the ID of the current session, or for generating a new session identifier. To increase the overall security of a session, generating a new ID sometimes can be quite useful, in order to avoid possible session ID interceptions from malicious users. In case you need to regenerate the ID of a current session, PHP also provides the “session_regenerate_id()” function, which can be used as follows:

echo ‘Old session ID is ‘.$oldid;
echo ‘New session ID is ‘.$newid;

And the corresponding output for this script would be similar to this:

Old session ID is 8245009bcf9e24a738804323e779a3b7
New session ID is 680ee3c504bdecaf270539b254dd97df

In this example, as its name suggests, the “session_regenerate_id()” function is used to generate a new ID for the current session, but the good thing is that session data is always maintained. This function is extremely useful for avoiding some issues related to session ID fixation, and should be utilized in order to increase the security of session handling scripts.

Now that you’ve learned how to use some helpful PHP session functions, handy for manipulating session IDs, it’s time to leap forward and continue exploring other functions included within the session management module. Please keep on reading to learn more.

{mospagebreak title=Ending a session: using the “session_destroy()” function}

In many situations, the logic of a particular PHP application requires that a specific session be terminated. In order to end an active session, PHP includes the “session_destroy()” function, which as the name indicates, destroys all the data associated with the current session. It’s worth noting that this function doesn’t unset any of the global variables tied to the session or the respective cookie. The use of this function is exemplified below:


As I said before, calling the “session_destroy()” function doesn’t delete the corresponding session variables or associated cookies. Thus a typical script, excerpted from the PHP manual, which destroys the current session along with all the session variables and the cookie associated to it, is listed below:

// destroy a session and all variables and cookies associated
with it.
$_SESSION = array();
   setcookie(session_name(),”, time()-48000,’/’);

In the above example, all the session variables are unset by the line:

$_SESSION = array();

while the corresponding cookie is deleted by the following code:

   setcookie(session_name(),”, time()-48000,’/’);

Additionally, all the registered session variables can be freed up with the “session_unset()” function. However, for a complete and secure deletion of the entire session, it’s recommended to use the “session_destroy()” function in conjunction with the superglobal $_SESSION array and the “setCookie()” function, as shown in the example above.

Nevertheless, there are some extra issues worth considering when ending sessions. In case the session ID is transmitted by cookies, they will be deleted as soon as the browser is closed. Bearing in mind this condition, you should configure (when possible) the “gc_maxlifetime” and “gc_probability” directives of the php.ini file, in order to instruct PHP to trigger its garbage collection mechanism, in accordance with the requirements of the application being developed.

Fine, at this point, you hopefully learned how to create and destroy an active session. Therefore, let’s move on to the next section and continue exploring a few more handy session functions.

{mospagebreak title=More session functions ahead: finding out the name of active sessions}

Just in case you didn’t know, the PHP session module offers many other helpful functions that can be used for obtaining the values of specific parameters, which are included within the set of directives of the php.ini configuration file. However, let me first show you another illustrative example, which displays the name of an active session:

echo session_name(); // displays PHPSESSID
// generate new session name
session_name(‘NEW_SESSION_NAME’); //displays NEW_SESSION_NAME
echo session_name();

As shown in the above script, the name of a session can be obtained by using the “session_name()” function. Very similar to the “session_id()” function that I described a few lines above, this function returns the name of the active session or assigns a new name to it.

After running the previous snippet, the output I get on my browser is the following:


If a new session is started with the same browser or even with a different one, the value returned by the “session_name()” function (without passing any argument to it) will always be “PHPSESSID,” because this is the default session name assigned in the php.ini configuration file.

Right, as you saw, the PHP session module exposes many interesting functions, either for retrieving or manipulating some parameters assigned as default values within the php.ini file. Keeping in mind this concept, join me in the next section to learn how these values can be used (or eventually changed) within your PHP scripts.

{mospagebreak title=Configuring the PHP session module: using some helpful session functions}

True to form, PHP also exposes a bunch of handy functions, aimed at returning and modifying some configuration parameters assigned as default values in the corresponding php.ini file. Over the next few lines, I’ll provide an overview of some of them, so you can have a clear idea of the role they play within the overall PHP session management module.

My list of examples begins with the “session_cache_limiter()” function, which returns the current setting of the “session.cache_limiter” directive, included in the php.ini file:

echo session_cache_limiter(); // default value is ‘nocache’
// set new cache limiter to ‘public’
echo session_cache_limiter();
// set new cache limiter to ‘private’
echo session_cache_limiter();

As shown above, the “session_cache_limiter()” function allows you to return or change the settings of the “session.cache_limiter” directive. This parameter controls how server responses will be cached by the browser, and its default value is “nocache.” This means that any client/proxy caching process will be disabled by default in PHP.

On the other hand, if a value of “public” is assigned to this parameter, it will allow proxies and the client to cache content respectively. A value of “private” will disable caching by proxies, but enable caching by the client. As you may have guessed, all the cache directives are handled directly by the appropriate HTTP headers.

Now, it’s time to have a look at another handy PHP session function, in this case “session_cache_expire(),” which returns and eventually modifies the settings of the “session.cache_expire” directive:

echo session_cache_expire();// default value is 180 seconds.
// set new cache expire value
session_cache_expire(20); // set cache value to 20 seconds.
echo session_cache_expire();

The above example shows how to use the pertinent “session_cache_expire()” function. Of course this function should be utilized when cache is enabled, and its default value is 180 seconds. If a new setting is assigned to this directive (the example sets a new value of 20 seconds for caching contents), the current value will be replaced with the new one.

Eventually, if you’re going to modify the “session.cache_expire” setting, keep in mind that the default value of 180 seconds is assigned to it with every new HTTP request, so you should change this directive each time a request is triggered and before calling the “session_start()” function.

Another helpful function that will allow you to modify the value assigned to PHP session storage modules is the “session_module_name()” function. In case you didn’t know about this feature, PHP can be configured to use different storage modules. As you saw before, the default storage module is “files,” but it’s possible to modify this setting, in order to use shared memory, by assigning a value of “mm,” or utilizing user-level callback functions, which are used in conjunction with the “session_set_save_handler()” function. For this last option, the assigned value should be “User.”

Now, here’s an example of how to use this function:

echo session_module_name().'<br />’; // default value is ‘files’
// set new module name
echo session_module_name(); // displays ‘user’

After demonstrating a simple implementation of the “session_module_name()” function, I’m going to finish (for the moment, so don’t worry) the discussion of PHP session-related functions, by explaining the combination of “session_set_cookie_params()/ session_get_cookie_params()” functions. Here’s a couple of examples that show how to use them:


In the above script, the “session_get_cookie_params()” function is used to return the settings of the following php.ini directives: “session.cookie_lifetime,” “session.cookie_path,” “session.cookie_domain” and “session.cookie_secure.” And the output I get on my browser is listed below:

Array ( [lifetime] => 0 [path] => / [domain] => [secure] => )

As you can see, the above function returns nicely the values assigned to the php.ini entries that I mentioned before. Its counterpart, the “session_set_cookie_params()” function, should be used in the following way:


And the output would look similar to this:

Array ( [lifetime] => 3600 [path] => /cookiepath/ [domain] => [secure] => )

In this case, this function sets new values for the corresponding php.ini settings, which will only be valid during the execution of the script in question. Thus, if you need to keep the new assigned values across different HTTP requests, the function should be called each time a new request is made. Simple, right?

At this point, I provided you with a pretty educational overview of some of the most important PHP functions included within the session management module. However, if you’re now thinking this is the end, I’m  afraid you’re wrong. There are still more topics to be covered related to PHP sessions, so be patient and read the upcoming articles.

To wrap up

In this first part of the series, I covered the basics of the PHP built-in session mechanism, as well as some of its many useful functions. However, as I said previously, I’m only scratching the surface of PHP sessions.

Over the next article, I’ll explain a few additional PHP session functions, aimed at achieving a greater level of control over the entire session mechanism. Caught your interest? Fine, see you in the next part!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye