Page 1 of 1

Pass object from script to script

Posted: Sun Mar 02, 2008 8:24 pm
by aquanutz
After looking around for what seemed like forever, I can't seem to get this correct. I initialize an object on page 1 and do everything I need to do and then when I save it in a session variable and try to use that very session varible on the next page, it will not access the class anymore. If I have it echo the variable it says "Object" so I know it's passing properly.

Code: Select all

 
//page 1
        session_start();
    include 'includes/user.php';
        
    if(isset($_REQUEST['username']))
        $username = $_REQUEST['username']; 
    else
        header('location:index.php?error=1');
    if(isset($_REQUEST["password"]))
        $pass = $_REQUEST["password"];
    else    
        header('location:index.php?error=2');
    //DO SOME MYSQL GARBAGE HERE
 
    $user = new user;
    $user->id = $id; //pulled back in mysql stuff
    $user->username = $username;
            
    $_SESSION['user'] = $user;  
        
    header('location:home.php');
 
and on page two i just try to recall the object and I can't

Code: Select all

 
    session_start();
    include "includes/user.php";
    $user = $_SESSION['user'];
    if(isset($_SESSION['user']))  //this returns YES
        echo 'yes';
    else
        echo 'no';
    echo $user-id;  //outputs nothing
    
 
Any thoughts??

Re: Pass object from script to script

Posted: Sun Mar 02, 2008 8:44 pm
by Sekka
I haven't actually done this, but I think this is what you need to do. I may be way off so test this or get someone to confirm it.

You need to serialise the object and then unserialise it on the other side. In other words, take the object as it is, convert it to a string, store the string in the session. And on the next page, take the string, and convert it back to the object.

Look at these two functions, serialise() and unserialise().

Re: Pass object from script to script

Posted: Sun Mar 02, 2008 8:48 pm
by Sekka
Also, line 9 on page two is wrong. You have $user-id, and you need $user->id.

Re: Pass object from script to script

Posted: Sun Mar 02, 2008 9:32 pm
by aquanutz
Thanks. I just unserialized it and now it's working.

As for the error in my code example, just an error in copying it into here, not actually an error in my code.

One thing I don't understand is that I thought session_register() was supposed to serialize and unserialize for you... Now in file 1 I just session_register('user'); and then on file 2 in order for it to work i have to use $user = unserialize($_SESSION['user']); . Oh well, it's working now. Thanks.

Re: Pass object from script to script

Posted: Sun Mar 02, 2008 10:36 pm
by Kraut
Hi,
session_register() is deprecated, just use session_start() and the $_SESSION array.
If you store objects in the session, be sure to include the *class* before session_start(), otherwise your *object* is a "zombie" without being linked to the class.