Reputation: 15
I have the following code which makes sure that the user is logged in. But I want to change to code to check for a specific user id. Can anyone help me with this?
function protect_page() {
if (logged_in() === false) {
header('Location: protected.php');
exit();
}
}
Upvotes: 1
Views: 91
Reputation: 3709
You can modify your function logged_in
and pass the specific user id to the function:
function logged_in($id) {
//this function checks if the user is logged in and has a specific id
return (isset($_SESSION['user_id']) && $_SESSION['user_id'] === $id) ? true : false;
}
You have to change your protect_page
function to fit the new logged_in
function:
function protect_page() {
if (logged_in(7) === false){
header('Location: protected.php');
exit();
}
}
Upvotes: 0
Reputation: 91
You could update your login function with an extra optional variable. If you don't specify the $user_id variable it will take the value 0, which will only check if the user is logged in. If you do specify a certain $user_id then the function will return true if the user is logged in and the $user_id matches the id stored in the session.
function logged_in($user_id = 0)
{
return (isset($_SESSION['user_id']) && (($user_id == 0) || ($_SESSION['user_id'] == $user_id))) ? true : false; //this function checks if the user is logged in and matches the given user identifier.
}
Upvotes: 2