我想创建一个没有数据库的管理员登录(这是一个非常简单的网站)这里是我的代码,这是安全还是易于使用我的会话?我怎样才能让它变得更好?
的index.php
<?php
include("auth.php");
if(!checkAuthentication()){
?>
<form method="post" action="?login=1">
<label for="username">Username</label>
<input type="text" id="username" name="username">
<label for="password">Password</label>
<input type="text" id="password" name="password">
<input type="submit" value="Login">
</form>
<?php
}else{
header("Location: protected_page.php");
exit();
}
的functions.php
<?php
session_start();
// Check if username and password matches
function authentication($username, $password){
if($username == md5("admin") && $password == md5("password")){
return true;
}else{
return false;
}
}
// Check if session data is still valid
function checkAuthentication(){
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
$result = authentication($_SESSION['username'], $_SESSION['password'], false);
}else{
$result = false;
}
return $result;
}
if(isset($_POST['username']) && isset($_POST['password']) && $_REQUEST['login'] == 1){
$username = md5(htmlspecialchars($_POST['username']));
$password = md5(htmlspecialchars($_POST['password']));
if(!authentication($username, $password)){
echo "Wrong Login.";
}else{
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("Location: http://localhost/login/protected_page.php");
exit();
}
}
?>
protected_page.php
<?php
include("auth.php");
if(!checkAuthentication()){
header("Location: http://localhost/login/index.php");
exit();
}
var_dump($_SESSION);
?>
感谢您的帮助!
答案 0 :(得分:3)
一些事情:
首先,您以纯文本形式将用户名和密码存储在PHP文件中。这不仅是一件糟糕的事情,也是一件难以维持的噩梦。让我们说你的脚本增长了,你需要50个用户来使用&#34; secure&#34;地区 - 维持这种噩梦。
其次,你的脚本不能很好地处理攻击(即蛮力)。我可以对它进行5次,50次,500次暴力攻击,它不会锁定我的&#34;帐户或IP地址。也许可以考虑一下。
密码应该存储在安全的地方而不是检查md5('password') == $_POST['password']
的值(例如),你应该检查md5($_POST['password']) == $hashedpassword
$hashedpassword
哪里www.yoursite.com
是存储的哈希值站点/在数据库中。这样,如果有人进入您的网站,那么就没有明文密码。
此外,我已经注意到您在index.php中包含了auth.php,但没有检查用户是否已经登录(例如,如果用户关闭了浏览器,则可能会发生这种情况无法记住受保护区域的完整URL。那么如果用户登录两次会发生什么?如果用户在登录时已登录,会发生什么情况?值得深思。
最后,考虑(出于UX用途)使用index.php检查用户是否已登录,如果没有,请将它们转移到login.php。这意味着如果他们失去连接(浏览器关闭)并转到{{1}},如果他们已经登录,他们可以看到那里的任何内容。这只是个人偏好,但值得研究。
最重要的:考虑使用框架。你有这么多理由,以及你在这里问我们是否安全应该绝对有理由告诉你它不是。网络上的洞太多了,请不要添加。除非你真的非常确定你正在做什么 - 抓住一个框架。