PHP:安全用户身份验证


PHP: Secure user authentication?

下面的代码检查管理员是否登录,并在网站上显示特殊的编辑框。为此,$show_tools将在整个脚本中使用。

 if (isset($user)){
        if($user->logincheck($_SESSION["loggedin"], "users", "user_password", "user_email")){
            $show_tools = true;
        }else{
            $show_tools = false;
        }
    }

之后使用$show_tools是否安全?例如:

<?php
  if ($show_tools){
    ?>
    <h1> Hello, administrator! </h1>
  <?php
  }
?>

使用原始$show_tools缺少封装。每个人都可以覆盖它,甚至是您自己,更不用说恶意黑客在您的程序中注入了代码。此外,随着程序的增长,您必须使其全局化。考虑以下方法:

function show_tools($flag = null) {
    static $value = false;
    if (is_bool($flag)) {
        // you can run other checks here too
        $value = $flag;
    }
    return $value;
}

用法:

// authenticate
show_tools(true);
if (show_tools()) { // if authenticated
    // show the tools
}
// deauthenticate
show_tools(false);

函数是不可重写的,所以没有人可以重写一个函数并在没有你的意愿的情况下修改你不想修改的部分。有了这种方法,你就安全了。没有它,任何事情都可能发生:

<?php
$show_tools = true;
include("your_insecure_script.php");
// Cool! I can see special editing boxes!
?>