php variable to include


php variable to include

我想知道在包含的文件中使用在父文件中声明的变量的最佳选择是什么。

当我想检查包含文件中的权限时,因为我不想将整个函数复制到任何文件中,我想检查权限。

我尝试了几种方法。哪个是最好的,还是我应该用另一种方法?

只包括:

<?php
// head file
$userlevel = 2;
$minimumlevel
include('testprivileges.php');
?>
<?php
// testprivileges file
if ($userlevel < $minimumlevel){
  die('no privileges');
}

<?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
?>

<?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);
?>

还是所有这些选项都不好?

你的第一个代码工作了,这是最佳实践。

你的第二个例子是坏的,因为:

include('checkprivileges.php?userlevel=$userlevel&minimumlevel=$minimumlevel');

不能工作。

你最后的代码也是一个不好的做法,因为你必须复制粘贴相同的函数到每个文件。这不仅是代码的重复,而且很难管理。

就像我说的,第一个代码效果最好。

一些注意事项:

$userlevel应该来自高层。您不应该在每个文件中都重新声明它。只需在全局config.php中设置一次即可。

$minimumlevel =当前页面的最小级别?

理想代码:

<?php
    $minimumlevel = 1;
    require_once ('includes/config.php'); // Contains $userlevel
    Checkrights($minimumlevel);
?>

显然也

function Checkrights($minimumlevel){
    global $userlevel;
    if ($userlevel < $minimumlevel){
      die('no privileges');
    }
}

config。

  require_once ('functions.php');
  $userlevel = 2;

按位权限制

如果你真的想要一个更好的权限系统,你可能想要点击这个关于按位权限系统的教程。我自己使用它,它非常简单。如果您在SQL中创建一个包含某些权限的新表,您可以为每个模块赋予每个权限。强烈推荐。

http://www.php4every1.com/tutorials/create-permissions-using-bitwise-operators-in-php/

只要在文件的开头包含它就可以了。

<?php
include("testprivileges.php");
//use to check privilege
?>