Purging session data on devel user switch If you have used the devel module, you'd probably know about the nifty Switch user tool that is available as a block for use in a site. It allows users with the required permission to switch from the block as any other user.

This is the API doc for the devel_switch_user method.

I notice that while switching between users, the session ID of the user as whom you initially logged in to the Drupal site for the first time is re-used for all switched users i.e. In {sessions}, the uid column is simply changed while {sessions}.sid or {sessions}.ssid persists.

A problem with this approach is that the session data ({sessions}.data) (saved using the $_SESSION superglobal) remains the same even for switched users which isn't good to test the application logic sometimes (at least not in my case).

Is there an elegant way to clear the session data of the old user on switch? If not, how can this be solved?
Problem is - $_SESSION was never really meant as temporary data storage. Proper and safe way is to use cache_set() to store data.

First argument, $cid is customary used as a string with sections separated with :, so in your case it should look about like that:

global $user;
// ...
cache_set('mymodule:' . $user-&gt;uid . ':' . $user-&gt;sid . ':kind_of_data',
          $data, 'cache', CACHE_TEMPORARY);
// ...
$data = cache_get('mymodule:' . $user-&gt;uid . ':' . $user-&gt;sid . ':kind_of_data',
                  'cache');


That way you will allow Drupal to benefit from database permanency, memcached speed, whatever you please. And by including uid of current user, you are sure data is well separated and no collisions will occur. Including session ID allows proper anonymous user handling. For logged in part $user-&gt;sid might be safe to ignore, depends if you want data to be shared between logged in seats or not.

If you use session id as a part of cache key, like above, entries will be only valid for one session. If your site has few users, obsolete cache entries are not a problem. And if you have many, you should store both sessions and cache in memcached, apc or similar technology anyway. Database is simply to slow for this. Memory based cache engines are very good at automatically destroying unused entries when needed, destroying them from code is a waste of time and effort.