Reputation: 67
I am wondering what is the best option to use variables in an included file who are declared in his parent file.
When I want to check privileges in an included file because I do not want to copy the whole function to any file I want to check the privileges.
I tried a few ways. Which is the best, or should I do it another way?
just include:
<?php
// head file
$userlevel = 2;
$minimumlevel
include('testprivileges.php');
?>
<?php
// testprivileges file
if ($userlevel < $minimumlevel){
die('no privileges');
}
or
<?php
//head file
$userlevel;
$minimumlevel
include('checkprivileges.php?userlevel=$userlevel&minimumlevel=$minimumlevel');
// i dont care this wont work. you understand what I try to do
?>
<?php
$userlevel = $_GET['userlevel'];
// and check for privileges
?>
or
<?php
// testprivileges function file
function testprivileges($userlevel, $minimumlevel){
if($userlevel < $minimumlevel){
die('no privileges');
}
}
?>
<?php
//head file
$userlevel = 2;
$minimumlevel = 3;
include('testprivilegesfile.php');
testpriviles($userlevel, $minimumlevel);
?>
or are all of those options bad?
Upvotes: 1
Views: 54
Reputation: 9692
Your first code works, and its the best practice.
Your second example is bad because this:
include('checkprivileges.php?userlevel=$userlevel&minimumlevel=$minimumlevel');
cant work.
Your last code is also a bad practice because you have to copy paste the same function to every file. Not only is that duplication of code, but also hard to manage.
Like I said, the first code works best.
Some notes though:
$userlevel Should come from high above. You shouldn't have to re-declare it in every file. Just set it once in a global config.php.
$minimumlevel = minimum level for current page?
Ideal code:
<?php
$minimumlevel = 1;
require_once ('includes/config.php'); // Contains $userlevel
Checkrights($minimumlevel);
?>
functions.php
function Checkrights($minimumlevel){
global $userlevel;
if ($userlevel < $minimumlevel){
die('no privileges');
}
}
config.php
require_once ('functions.php');
$userlevel = 2;
If you are really into a better permission system you might want to hit this tutorial about the bitwise permission system. I use it myself and its VERY simply. If you create a new table in SQL containing some permissions, you can give privileges PER module per sé. Highly recommended.
http://www.php4every1.com/tutorials/create-permissions-using-bitwise-operators-in-php/
Upvotes: 1
Reputation: 774
Simply just include in the beginning of the file if you will use it.
<?php
include("testprivileges.php");
//use to check privilege
?>
Upvotes: 0