How To Store Session Cookies in Drupal?

We were playing around with Drupal recently and noticed that there aren’t much information in regarding on how to setup sessions in Drupal.

Here is our setup. We have created a Drupal page, which has PHP codes in it that will submit a form which then will return the variables back into the same page. Searching through the Drupal site, we couldn’t find much information on this topic or that the information was not clear. Anyway, we have finally found something that is useful. Unforunately, using cookies session wasn’t the way we wanted but at less it worked.

Here is how to save sessions in a Drupal page that you created.

First, you will need to create and set your variables by using the “setcookie(‘cookieName’, ‘cookieValue’, 0, ‘/’);

After that, all you need to do is by calling the “$_COOKIE[‘CookieName’];” to display the cookie value.

e.g.

setcookie(‘number’, ’56’, 0, ‘/’);
print $_COOKIE[‘number’];

Output:
56

 

Looks like Managing Session in Drupal is a little bit different than the normal PHP session management.

Most of the Drupal session settings are located in three places.

Drupal Settings Location

– .htaccess file
– settings.php file
– bootstrap.in file

How to setup session in Drupal?

– To store session variables in Drupal, use the following code example.

global $user;
$user->yourSessionName = ‘yourSessionvalue';
user_save();

How to view session variables in Drupal?

$user->session;

How to store persistent variables in Drupal?

In Drupal, you can store your variables in the ‘variable’ table. To access this, you will need to reference the global $conf.

E.g.

global $conf; <– set/access the variable table
variable_set($yourVar, $yourValue); <– set the persistent variable
variable_get($yourVar, $default); <– get the persistent variable
variable_del($yourVar); <– delete the persistent variable

visit drupal for more info on persistent variables.

Known Drupal Session Issues:

Can not display session variables for anonymous users in Drupal

– To display session variables for anonymous users, make sure your drupal user database has an id for anonymous user (UID = 0). This is the user ID that Drupal check against to see if an user is anonymous or authenticated.

Make sure NOT to include the session_start(); in your code. Session Management in Drupal doesn’t need this. It is already declared.