Inactive User Enforce To Login (SESSION Expired) Or Limmit The Resource

Listen Audio
0:00 / 0:00
Inactive user enforce to login (SESSION expired) or Limmit the resource image

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.



Leave a non public comment how to improve it.



Characters Remaining

We are sorry for your bad experience. Leave a non public comment how to improve it.



Characters Remaining

Related Posts (11)

How to create a custom archive page template on your website layout image
Test the video layout design(Upload and Store video to MySQL Database with PHP) image
How to set the expiry period for a reset password link. image
Getting User Device Location and Updating Database image
Send A verification email when a new user registered  image
How to Send Verification link when a new user register image
How to limit the number of login attempts  image
How to limit the number of login attempt using PHP part 2(PHP functionality) image
Download file using PHP image
How to count page viewers based on the IP Address of the device image
Pagination in PHP image

Share this on

Search


Archives

No archives data found yet in 2016.

Find Us on Facebook

Subscribe for new updates



Back to Top