tl;dr:
Use header("Location: somepage.php");
to redirect based on $_SESSION['user_type']
or SQL query at the beginning of each page. No need for separate logins.
I am assuming mysql.php
is your database file:
mysql.php
<?php
$mysqli = new mysqli('localhost', 'username', 'pass', 'db', port);
if(mysqli_connect_errno()) {
echo "DB Error!"; exit();
}
?>
At the top of all pages, add something like the following. This will redirect to a login page if the user is not logged in. Lots of assumptions (integer ID, SESSION variables etc), but you get the idea:
<?php
session_start();
require("mysql.php");
// If not logged in, go to login
if(isset($_SESSION['user_id']) && $_SESSION['logged_in']) {
if($result = $mysqli -> prepare("SELECT id FROM `USER` WHERE id = ? AND session_id = ? LIMIT 1")) {
$session_id = session_id();
$result -> bind_param("i", $_SESSION['uid']);
$result -> execute();
$result -> store_result();
if($result -> num_rows != 1) {
header("Location: login");
exit();
}
}
else {
header("Location: login");
exit();
}
}
else {
header("Location: login");
exit();
}
?>
In the same way, you can redirect if a logged in user is an admin or member (using something like $_SESSION['user_type']
, which is set upon login). Because you're new, here's some more code:
login.php
<?php
session_start();
require("mysql.php");
// If already logged in, redirect to admin or members based on session variable.
// ...
//
// If a login form has been submitted (assuming you're logging in from a POST)
if(isset($_POST['submit'])) {
if($_POST['username'] && $_POST['password']) {
if($result = $mysqli->prepare("SELECT id, username, user_type, password FROM `USER` WHERE username = ? LIMIT 1")) {
$result -> bind_param("s", $_POST['username']);
$result -> execute();
$result -> store_result();
if($result -> num_rows == 1) {
$result -> bind_result($id, $username, $user_type, $bcrypted);
$result -> fetch();
if(password_verify($_POST['password'], $bcrypted)) {
session_regenerate_id(); // Avoid Session Fixation Attack
$session_id = session_id(); // Update the USER table using this
$_SESSION['user_id'] = $id;
$_SESSION['username'] = $username;
$_SESSION['user_type'] = $user_type;
$_SESSION['logged_in'] = true;
// Log some data to your DB, login time, ip, etc
header("Location: ".($_SESSION['user_type'] == 'admin' ? 'admin.php' : 'member.php'));
exit();
}
}
}
}
}
?>
<html> ...
Quite a few points in there. Regenerate session IDs before actual 'login', use bcrypt for passwords, assuming you understand parameterized statements for MySQL, there's also a ternary operator in there. Don't forget a logout page:
logout.php
<?php
session_start();
$_SESSION['logged_in'] = False;
$_SESSION = array();
session_destroy();
header("Location: login.php");
?>
I hope at least some of this helps. There's a million things I haven't covered, but you can learn a lot from material already on the web. Good luck!