I would like to ask your advice on my simple code to login and registration sessions.
In the User class, login function:
public function login($username, $password){
$this->db->query("SELECT * FROM users WHERE username = :username AND status = :status LIMIT 1");
$this->db->bind(':username', $username);
$this->db->bind(':status', 1);
$row = $this->db->single();
$count = $this->db->rowCount();
if ($count > 0) {
if (password_verify($password, $row['password'])) {
$_SESSION['session'] = [
'id' => $row['id'],
'username' => $row['username'],
'email' => $row['email'],
];
return true;
} else {
return false;
}
}
}
check logged:
public function isLoggedIn() {
if (isset($_SESSION['session'])) {
return true;
}
}
And login page with check logged:
if ($user->isLoggedIn()) {
header('Location: index.php');
exit();
}
if(isset($_POST['login'])){
//Retrieve the field values from our login form.
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$password = !empty($_POST['password']) ? trim($_POST['password']) : null;
if($user->login($username, $password)) {
header('Location: index.php');
exit();
} else {
$message[] = 'We found problems with the login, please try again.';
}
}
login()
on line 100 it creates a new session. Innewsession()
(line 248 ff.) it creates a new session and saves it to the db. This session is tied to the user and IP address. Although session generation is not optimal (microtime()
is not a good example), it generates unique sessions and invalidates them, if they expire (checksession()
, line 370 ff.). I wouldn't recommend the whole class because of weak security but the base is very robust. \$\endgroup\$ – GiantTree May 14 '16 at 11:19