First when a user logged in put the logged in user in to a session
$sql = "SELECT * FROM users WHERE (email='$email' OR username='$email') AND password='$password' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
// get id of created user
$reg_user_id = $row['id'];
// put logged in user into session array
$_SESSION['user'] = getUserById($reg_user_id);
// do your code here
}
the getUserById() function is used to get a session user information
// Get user info from user id
function getUserById($id)
{
global $conn;
$sql = "SELECT * FROM users WHERE id=$id LIMIT 1";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);
// returns user in an array format:
return $user;
}
then check if a user logged in or not using the IsLoggedIn(0 function as below
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
---------you may also restrict a resource based on a user type---------
function isLoggedIn()
{
if (isset($_SESSION['user']['role']) == "Admin" || isset($_SESSION['user']['role']) == "Author"){
return true;
}else{
return false;
}
}
finally write the following line of code at the beginning of your home page/ admin page based on your need.
if (!isLoggedIn())
{
$_SESSION['messages'] = " You must log in first to access this page.";
header('location: ' . BASE_URL . 'login');
}
that's it all done.