I've seen two types of ways to handle user logins, and I'm not sure which one is a better method...
METHOD 1
Login once, store user id in the session, and retrieve it for every subsequent check (Query only once)
Code: Select all
<?php
function login($username,$password) // Assume encryption and escaping
{
$result = $db->query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$password';");
if($result->rowCount==1)
{
$user = $result->fetch();
$_SESSION['user_id'] = $user['id'];
return $user['id'];
}
return false;
}
function checkLogin()
{
if($_SESSON['user_id']){
return $_SESSION['user_id'];
}
return false;
}
?>Store username and password in the session, and login on each page (Query every time)
Code: Select all
<?php
function login($username,$password) // Assume encryption and escaping
{
$result = $db->query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$password';");
if($result->rowCount==1)
{
$user = $result->fetch();
$_SESSION['username'] = $user['username'];
$_SESSION['password'] = $user['password'];
return $user['id'];
}
return false;
}
function checkLogin()
{
if($_SESSON['username'] && $_SESSION['password'])
{
$username = mysql_real_escape_string($_SESSION['username']);
$password = mysql_real_escape_string($_SESSION['password']);
return login($username,$password);
}
return false;
}
?>It seems that Method #2 is more secure, and security is more important than saving that one extra query. However, my question is, is it really more secure? Is there really a diference? Is there any way that Method #1 could prove less secure than #2?
According to me Method #1 is only insecure if sessions could be faked (Can they?)... then anyone could just plugin a false user id and login as that person. But I'm not sure if sessions can be faked this way. If not this, I can't think of any other reason why Method #1 would be insecure.
Any comments?