我希望有人可以看一下我的第一个PHP登录脚本,并对我可能做错了什么以及它是否真的安全给我一些建设性的批评。谢谢。
我不确定我是否正确使用了密码rehash。
if (isset($_POST['submit'], $_POST['username'], $_POST['password']))
{
$username = null;
if (isset($_POST['username'])) $username = strip_tags(trim($_POST['username']));
$password = null;
if (isset($_POST['password'])) $password = strip_tags(trim($_POST['password']));
$sql = "SELECT * FROM login WHERE username=?";
$get = $connect->prepare($sql);
$get->execute(array(
$username
)); // Execute the query
if ($get->rowCount() === 1)
{
$row = $get->fetch(PDO::FETCH_ASSOC); // Fetch the result
$db_username = $row['username'];
$db_password = $row['password'];
if ((password_verify($password, $db_password)) && (strlen($username) >= 5) && (strlen($username) <= 10) && (strlen($password) >= 5) && (strlen($password) <= 12))
{
if (password_needs_rehash($password, PASSWORD_DEFAULT))
{
$hash = password_hash($password, PASSWORD_DEFAULT);
$sql = "SELECT * FROM login WHERE username=?";
$get = $connect->prepare($sql); // Use prepare to prevent SQL injection
$sql = "UPDATE login SET password=? WHERE username=?";
$statement = $connect->prepare($sql);
$statement->execute(array(
$hash,
$username
));
}
$_SESSION['auth'] = $db_username;
session_regenerate_id(true);
$sql = "UPDATE login SET last_login=?, ip=? WHERE username=?";
$statement = $connect->prepare($sql);
$statement->execute(array(
$dt,
$ip,
$username
));
$sql2 = "INSERT INTO LOG (username,lastlogin,ip) VALUES (:username,:lastlogin,:ip)";
$statement = $connect->prepare($sql2);
$statement->execute(array(':username'=>$username,
':lastlogin'=>$dt,
':ip'=>$ip
));
reloadPage();
}
else
{
$loginmsg = 'Wrong Username / Password';
}
}
else
{
$loginmsg = 'Wrong Username / Password';
}
}
答案 0 :(得分:1)
没有。 1缺陷
$username = null;
if (isset($_POST['username'])) $username = strip_tags(trim($_POST['username']));
$password = null;
if (isset($_POST['password'])) $password = strip_tags(trim($_POST['password']));
尝试
$username = null;
if (isset($_POST['username']))
{
$username = strip_tags(trim($_POST['username']));
}
$password = null;
if (isset($_POST['password']))
{
$password = strip_tags(trim($_POST['password']));
}
没有。 2缺陷
始终使用algo contants
和password_hash()
以更好地使用。
if (password_needs_rehash($password, PASSWORD_DEFAULT))
{
$cons = array('cost' => 12);
$hash = password_hash($password, PASSWORD_DEFAULT, $cons);
$sql = "SELECT * FROM login WHERE username=?";
其他所有人对我都好。