Re: Issue with the casting of a SESSION variable



AndreH wrote:
Good day,

I have the a bit of an issue with retrieving an object from php's
session.

I set a session variable "user" from the class User as follows:
$user = new User();
// ... do some stuff to $user
$_SESSION['user'] = serialize($user);

And try to retrieve the variable again later:
$user=(User)unserialize($_SESSION['user']);

Why? A session already serializes its values when stored, no need to do it twice. You can perfectly store an object in a session, as long as you've loaded the class definitions before session_start().

Keep in mind not every object can be serialized, see the manual:
http://nl2.php.net/serialize
"serialize() handles all types, except the resource-type. You can even serialize() arrays that contain references to itself. Circular references inside the array/object you are serialize()ing will also be stored. Any other reference will be lost."

Something not serializable is by default not storable in a session, allthough you could employ the __sleep() & __wakeup() methods to remove any unserializable content, and recreate them on unserialize.
--
Rik
.



Relevant Pages

  • Re: Unable to Serialize
    ... namespace MyFunctions ... you posted nothing to serialize. ... Could this be a problem with Web Services? ... I have an object I am unable to put in my session. ...
    (microsoft.public.dotnet.framework.aspnet)
  • SessionState SQLServer Error
    ... "Unable to serialize the session state. ... (Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, ... graph, HeaderinHeaders, __BinaryWriter serWriter, Boolean fCheck) +683 ...
    (microsoft.public.dotnet.framework.aspnet)
  • SessionState SQLServer Error
    ... "Unable to serialize the session state. ... (Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, ... graph, HeaderinHeaders, __BinaryWriter serWriter, Boolean fCheck) +683 ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: SQL Server session not working...
    ... non-serializable object, etc. in this case you must be redesign you session ... you'd think, when asp.net tried to serialize session data, it would list the ... itself then you will have to manually serialize those objects. ... on a server which uses Load Balancer. ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: Saving DataTable to session vs saving a Custom object.
    ... The web app we are developing is a portal to a large database. ... We are using SQL Server to store our session variables, ... If your using a state server or a SQL ... on the other hand serialize as little more than ...
    (microsoft.public.dotnet.languages.csharp)