I have two modules. The first module is for custom login form and the other is for custom user pages. I want to store a session variable from the first module and later to call on the second module. Let's say my field from the first module is:

function custom_login_form($form, &$form_state) {

    $form['custom_field'] = array(
       '#type' => 'textfield',
       '#title' => 'Custom field',

   return $form

and this is the callback from my second module:

    function custom_user_pages() {
       $The_session_stored_field = 'some_value';


How can I store the custom_field with session and how to call it on the second module?

EDIT: My custom modules are connecting with web service and all the information I'm passing with XML. With simplexml_load_string() I'm getting all the data. Now I've used $_SESSION, but I have some error:

"Exception:Serialization of "SimpleXMLElement" is not allowed in session_write_close()...

EDIT2:In my first module I've set SESSION like this:

$_SESSION['custom_field'] = $custom_field;

On the other module I've set $custom_field = $_SESSION['custom_field'];

Is this a right approach?

Yes, I've got an error that's not related with session, because simplexmlelement cannot be serialized like that. Maybe I should open a new thread for that.

  • do you sure variable do your job? there is very different between SESSION and variables that store in db ???????
    – Yuseferi
    Commented Feb 17, 2014 at 10:33
  • Yes, you're right. I've marked the answer too soon. I've edited my thread, so pls check that. Commented Feb 17, 2014 at 10:34
  • Your latest edit has got nothing to do with the $_SESSION and your initial question, but with the serialization of XML.
    – Wtower
    Commented Feb 17, 2014 at 10:39
  • 1
    A SimpleXMLElement object cannot be serialized, as @Wtower says that's not a session problem - you'll need to cast it to a string first
    – Clive
    Commented Feb 17, 2014 at 10:42

2 Answers 2


In submit of form store your data in session variable $sid with _drupal_session_write('mysession', $value); and in every where you want read it with _drupal_session_read('mysession');

you shold start session before you write or read session variable like php.

_drupal_session_write($sid, $value);

There is a workaround to make SimpleXMLElement object serialized by encoding it into JSON format (as posted here):

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

This is especially useful for caching which usually fails, so the workaround is to do:

cache_set($cid, json_encode($data));

Alternatively find out if your service supports JSON format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.