0

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-->
?>
Gaurav
  • 29
  • 9
  • `` This is an html comment, which can be viewed by anyone looking into the source. It's not the best practice revealing personal business. Use `/* my comment */` instead – Giacomo Pigani Apr 13 '14 at 09:50

2 Answers2

0

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

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • I tried to use it but no luck. It still gets included and there is no other way it cannot get included twice even by using require_once in both files. – Gaurav Apr 13 '14 at 09:44
  • Hmm... it looks like your include file is... defining variables? That's not good. Consider using a static method, like `Core::logged_in()` instead - that way you don't have to pass references around and can get it from anywhere. – Niet the Dark Absol Apr 13 '14 at 09:46
0

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 */
Community
  • 1
  • 1
Jorge Y. C. Rodriguez
  • 3,394
  • 5
  • 38
  • 61