简体   繁体   中英

PHP: Cannot restrict access to page

I have header.php which contains init.php which starts the session and further contains all the functions and classes for database queries. I have header.php included in every file because it contains the menu. The menu is updated if the user is logged in or not. This works fine.

But my problem is: when including header.php on another page, I am unable to further include init.php as it has already been included in header.php, and so I cannot call any functions in those pages which I certainly need to.

For example, there is a page called new.php (which also contains header.php) where admin can add new entries into the db; and I want it accessible only to the admin. So what I wanted to do was to check if the rank of the user is 2 otherwise redirect. So to retrieve the rank of the user I need to use the function inside a class in init.php. To do that, if I place the logic code below header.php (in new.php) because only then I will be able to access the objects of init.php, I am unable to use the header() function because headers are already sent. And if I try to declare it above header.php (in new.php) by including the init.php file again, it gives me: multiple declaration error of class is not allowed.

Here is the piece of code:

header.php

<?php
      require 'core/init.php';
      if($general->logged_in()){
        $user = $user->userdata($_SESSION['uid']);
        $username = $user['username'];
        $rank = $user['rank'];
      }
?>
<!--Menu bar html below-->

new.php

<?php  
    include 'includes/header.php';
    <!--Check for the rank and redirect if invalid-->
?>

Take a look at require_once . It may be the answer to your problems.

I think include_once you can read about it here and from this other good question you can learn what is difference when it comes to speed and performance in the server, and which one is more expensive to execute. also this wrong

<!--Check for the rank and redirect if invalid-->

comments in php are like this

 /* Check for the rank and redirect if invalid */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM