Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serialize() and $_SESSION [duplicate]

Once the user is authenticated, I serialized the class object and stored it in a session. However, I cant seem to print its output even after using unserialize().

Creating the session variable:

if(!isset($_SESSION['myObj']) && empty($_SESSION['myObj'])) {
$myObj = new User($row['user_id'], $row['username'], $row['user_level']);
$_SESSION['username']= $myObj->usr_name;
$s_Obj = serialize($myObj);
$_SESSION['myObj'] = $s_Obj;

Accessing from a different page, no output:

$sObj = $_SESSION['Obj'];
$myObj = unserialize($s_Obj);
echo $myObj->usr_name;

This works however, so there's nothing wrong with my class. I am also using session_start() in both pages.

echo $_SESSION['username'];

Class user:

<?php 

class User{
    public $usr_id;
    public $usr_name;
    public $usr_level;
    public $last_access_login;

    public function __construct($id, $usr_name, $usr_level) {
        $this->usr_id = $id;
        $this->usr_name = $usr_name;
        $this->usr_level = $usr_level;
        $this->last_access_login = date("F d Y H:i:s.",time());
  }
}
?>

Edit:

This is my vardump

array
  'myObj' => 
    object(__PHP_Incomplete_Class)[1]
      public '__PHP_Incomplete_Class_Name' => string 'User' (length=4)
      public 'usr_id' => string '3' (length=1)
      public 'usr_name' => string 'student' (length=7)
      public 'usr_level' => string '3' (length=1)
      public 'last_access_login' => string 'November 26 2011 20:12:38.' (length=26)
  'url' => string '/researchportal/proposal' (length=24)
like image 831
user478636 Avatar asked Nov 26 '11 19:11

user478636


2 Answers

Inital page:

$s_Obj = serialize($myObj);
$_SESSION['myObj'] = $s_Obj;

should be

$_SESSION['myObj'] = $myObj;

Next page:

$sObj = $_SESSION['Obj'];
$myObj = unserialize($s_Obj);

should be

$myObj = $_SESSION['myObj'];

In addition, try declaring your classes before your call to session_start().

like image 130
kevinji Avatar answered Oct 19 '22 00:10

kevinji


Your unserialized object is being unserialized as an instance of __PHP_Incomplete_Class_Name because you are not including the definition of the User class prior to unserializing it. See Object Serialization. You must include the definition of the User class before you try to unserialize it.

like image 36
John Watson Avatar answered Oct 18 '22 23:10

John Watson