Page 1 of 1

why serialize ??

Posted: Mon Dec 01, 2014 11:53 pm
by gautamz07
checkout the below loggin function :

Code: Select all

	public function login($username, $password)
	{

		$hashedPassword = md5($password);
		$result = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$hashedPassword'");

		if(mysql_num_rows($result) == 1)
		{
			$_SESSION["user"] = serialize(new User(mysql_fetch_assoc($result)));
			$_SESSION["login_time"] = time();
			$_SESSION["logged_in"] = 1;
			return true;
		}else{
			return false;
		}
	}
i don't really get this line :

Code: Select all

$_SESSION["user"] = serialize(new User(mysql_fetch_assoc($result)));
Why is serialize being used ???

Re: why serialize ??

Posted: Tue Dec 02, 2014 1:40 am
by requinix
Probably because the developer didn't know that session data is serialized automatically. Generally.

To the broader question, PHP can't store an object in a file (where sessions are normally stored) or a database (the second-most common place) - there's too much stuff in memory. So it serializes the object, which involves storing the name of the class and the values of the member variables. Later it unserializes the object by setting up a new object and filling in the variables.