User Account Class in PHP 2
I started up an account class in my previous post, but I left out a way for the user to authenticate! Let’s fix that…
Authenticate
public function authenticate($group_id = 0) {
$dbconn = @Database::grab();
// They must have ALL three cookies set from the login function, otherwise something went wrong!
if( !isset($_COOKIE['id']) && !isset($_COOKIE['cookie']) && !isset($_COOKIE['name']) )
{
return false;
}
// Sanitize
$id = safe($dbconn, $_COOKIE['id']);
$cookie = safe($dbconn, $_COOKIE['cookie']);
$username = safe($dbconn, $_COOKIE['name']);
// Make sure they have a valid cookie value first! (64 characters long in our case)
if( strlen($cookie) > 63 )
{
// Check the values in the DB with a quick query
$query = "SELECT id, username, cookie, group_id FROM users WHERE
id = ".$id." AND
cookie = '".$cookie."' AND username = '".$username."' AND group_id >= $group_id LIMIT 1";
$queryData = $dbconn->query($query);
}
if( $queryData )
{
if( $queryData->num_rows > 0) {
$data = $queryData->fetch_object();
$this->group_id = $data->group_id;
$this->user_id = $data->id;
$this->username = $data->username;
return true;
}
}
// They failed to authenticate! Wrong username/pass?
$this->logout();
return false;
}
There you have it. Basically, check to make sure they have all the cookies you set in your login function. If any are missing, fail. Then, we write a query to check the credentials from the cookies to see if they match what’s in the database. If not, clean up their cookies with $this->logout() and return false. That reminds me, here’s the code for logout:
Logout
public function logout() {
$dbconn = @Database::grab();
if(isset($_COOKIE["id"]) && isset($_COOKIE["cookie"]))
{
$id = safe($dbconn, $_COOKIE['id']);
$cookie = safe($dbconn, $_COOKIE['cookie']);
// Set the cookie to null in the database
$query = "UPDATE users SET cookie = 0 WHERE id = ".$id." AND cookie = '".$cookie."'";
$dbconn->query($query);
}
// Expire our cookies by setting the time to 1 second after the EPOCH
setcookie("hpname", "", 1, "/" );
setcookie("hpid", "", 1,"/" );
setcookie("hpcookie", "", 1,"/" );
// Unset them immediately
unset($_COOKIE['hpname']);
unset($_COOKIE['hpid']);
unset($_COOKIE['hpcookie']);
}
There you go. What’s missing now? We just need a forgot password function and we’re good to go.
Lost on this tutorial? Try going back to part 1

February 12th, 2010 at 5:51 PM
Why not use sessions instead of cookies, just wondering if that was a design decision or not.
February 12th, 2010 at 7:35 PM
It’s funny you should mention that. I was just using sessions to authenticate on our SE2 project earlier today.
It was a design decision early on to keep things as simple and basic as possible. Though, it seems like a lot of systems (from googling in the past) use session AND cookies. I think that may be the next step in some of my future projects!