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{
开发者_JS百科 $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!
?>
精彩评论