why serialize ??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

why serialize ??

Post 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 ???
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: why serialize ??

Post 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.
Post Reply