Home > Back-end >  How to Restrict Access to a Page with PHP if statement
How to Restrict Access to a Page with PHP if statement

Time:09-18

I have a PHP project with user account status in the database. It contains status such as active, inactive, suspended etc. I need an if statement in the index page that can Restrict access to a particular page or link if the account is set to inactive.

Your response is great appreciated. Thank you in advance

CodePudding user response:

If you wanted to prevent links to certain pages from showing to users that didn't have a status of active, you might do something like this:

<!-- Non active state links -->
<a href="/about">About us</a>
<a href="/contact">Contact us</a>

<!-- Active state only link -->
<?php
  if($user->status === 'active'){
    echo '<a href="/admin">My Account</a>';
  }
?>

Then on each of the restricted pages themselves, you might do something like this:

<?php
   if($user->status !== 'active'){
      echo "Forbidden!";
      die();
   }

   *** The rest of your code here ***
?>

To prevent access to a particular page, you need the logic to be present on that page, you can't control who can access what solely from the index page.

CodePudding user response:

I suppose you are using Native PHP:

At the file which contains the code you want to restrict:

<?php
if(!$myUser->isActive){ //User is not active
    header(File you want to redirect in case is not active.php)
}
  • Related