So I'm currently working on a plattform for Dance Trainer to register for our Dance Contest... The Trainers Create an Account, Log in with that Account -> if the mail and passwort is correct some session variables will be initiated, inside those variables are the users id, mail, etc. and the users "role" (admin or user / 1 or 2) after those variables have been initiated the user will be forwarded to the actual user area website. That side will now check if the session variables are set and if the user role is high enough to visit that page, if not forward the user to the admin or login page (admin if role = 2 and login if role != 1 or 2) But the variables do not save on the first login attempt, you have to log in twice....
here is my code
Login Page:
session_start();
include('connect.php'); //mysql connection function
if (isset($_POST["login"])) // check if login attemp exists
{
//get mail from form
$mail = mysqli_real_escape_string($verbindung, $_POST["mail"]);
//get password from form
$pw = mysqli_real_escape_string($verbindung, $_POST["pw"]);
//check if user exists in db
$sql = "SELECT * FROM user_db WHERE mail = '$mail'";
$query = mysqli_query($verbindung, $sql);
while ($user = mysqli_fetch_object($query))
{
if (password_verify($pw, $user->password))
{
// set session variables
$_SESSION["login"] = $user->acc_type; //role
$_SESSION["id"] = $user->id; //id
$_SESSION["vorname"] = $user->vorname;
$_SESSION["mail"] = $user->mail;
$_SESSION["nachname"] = $user->nachname;
}
}
}
// check if login attempt succeded and get the user role
if ($_SESSION["login"] == 1)
{
// if role is user goto user page
echo '<meta http-equiv="refresh" content="100; URL=user" />';
}else if ($_SESSION["login"] == 2)
{
if role is admin goto admin page
echo '<meta http-equiv="refresh" content="100; URL=admin" />';
}
User/Admin Page (both with identical code/error):
session_start();
if ($_SESSION["login"] == '2')
{
//goto admin if user is admin
echo '<meta http-equiv="refresh" content="0; URL=../admin">';
}else if ($_SESSION["login"] != '1')
{
//goto login if user is neither role 1 or 2
//this one triggers allways if it is your first attempt to login
//it behaves like the session didnt start on the login page but i dont know why
echo '<meta http-equiv="refresh" content="0; URL=../">';
}