简体   繁体   中英

PHP: Secure user authentication?

Code below checks if administrator is logged in and shows special editing boxes on website. For that, $show_tools will be used throughout the script.

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

Is it secure to use $show_tools afterwards? For example:

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

Use of raw $show_tools lacks encapsulations. Everyone can overwrite it, even you by mistake, not mentioning a malicious hacker having injected code in your program. Plus you would have to make it global as your program grows. Consider the following approach:

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

Usage:

// authenticate
show_tools(true);

if (show_tools()) { // if authenticated
    // show the tools
}

// deauthenticate
show_tools(false);

Functions are meant to be non-overridable, so no one can overwrite a function and alter what you do not want to be altered without your will. With this approach you're safe and secure. Without it, anything can happen:

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

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