I am currently busy with my own login script that is simple but also safe enough to fit my goal. It uses MySQL to save the usernames and passwords. Now I came to the point of using sessions to be able to check whether a user is logged in, just like it can be found in many tutorials. So far I came up to this, but I'm just not sure whether this is a proper/safe way to do this.
<?php
$db = new PDO('mysql:host=HOST;dbname=DATABASE;charset=UTF-8',
'USERNAME',
'PASSWORD',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
if(isset($_POST['username']) && isset($_POST['password'])){
$select = $db->prepare("SELECT id, username FROM vwo5_users WHERE username=:username AND password=:password");
$select->execute(array(':username' => $_POST['username'], ':password' => $_POST['password']));
$amount = $select->rowCount();
$result = $select->fetch(PDO::FETCH_ASSOC);
$user_id = $result['id'];
$user_name = $result['username'];
if($amount >= 1){
session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $user_name;
echo 'Logged in';
}
else{
echo 'Wrong login data';
}
}
else{
header('Location: dbtestform.php');
}
?>
I would then check at a secured page whether the id and username from the session go together in the database as well, but I can't put my finger on the point of this being safe or not. I know it's being described all over the internet, but no source I found made it more clear to me.