After trials and errors I have found it is safer not to pull the password out of MySQL.
Here’s is the login script that I used
public function read($email, $password) {
$db = DB::getInstance();
$pdo = $db->getConnection();
/* Setup the Query for reading in login data from database table */
$this->query = 'SELECT id FROM members WHERE email=:email AND password=:password';
$this->stmt = $pdo->prepare($this->query); // Prepare the query:
$this->stmt->execute([
':email' => $email,
':password' => hash('whirlpool', $password)
]); // Execute the query with the supplied user's parameter(s):
$this->stmt->setFetchMode(PDO::FETCH_OBJ);
unset($password);
if ($this->user_id = $this->stmt->fetchColumn()) {
return $this->user_id;
} else {
return FALSE;
}
}
Just substitute $ for $this-> and get rid of of the public declaration. Then you will basically have a function.
This is the script that grabs the user’s id
$submit = filter_input(INPUT_POST, 'submit', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (isset($submit) && $submit === 'enter') {
//echo "<pre>" . print_r($_POST, 1) . "</pre>";
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$id = $login->read($email, $password);
if ($id) {
after_successful_login($id);
header("Location: member_page.php");
exit();
} else {
//echo "You're a Failure!<br>";
/* The above for local testing only */
/* I would either log in the failed attempt or just give a generic message
to the user */
}
}
I didn’t really write the following after successful login function but modified it to fit my needs:
// Actions to preform after every successful login
function after_successful_login($id = NULL) {
// Regenerate session ID to invalidate the old one.
// Super important to prevent session hijacking/fixation.
session_regenerate_id();
$lifetime = 60 * 60 * 24 * 7;
setcookie(session_name(), session_id(), time() + $lifetime);
$_SESSION['user_id'] = $id;
// Save these values in the session, even when checks aren't enabled
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$_SESSION['last_login'] = time();
}
The main thing is to store a password hash in the database table and not to pull it out of it. I personally would NOT use password_verify and password_hash functions, but use the hash() function. (php.net will explain it better than I can) I personally don’t store anything in session other the the user’s id and when I need that information I just read it in from the database table using the user’s id. The less you have of the user’s information in sessions the better your are security wise, but nothing is 100 percent secure on the internet. Though you should make it as secure as possible.