我已经制作了一个正在运行的登录脚本(请参阅下面的代码)
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$db = mysqli_connect("localhost", "root", "ovlovw8", "reparatie");
if (isset($_POST['submit'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$password = md5($password);
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 1) {
$_SESSION['message'] = "je bent ingelogd";
$_SESSION['username'] = $username;
header("location: overzicht.php");
} else {
$_SESSION['message'] = "verkeerde inlog gegevens";
}
}
但是现在我想添加多个用户级别,并且我已经为此创建了一个脚本,但它不起作用。
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$db = mysqli_connect("localhost", "root", "ovlovw8", "reparatie");
if (isset($_POST['submit'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$password = md5($password);
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 1) {
switch ($role) {
case '1':
$_SESSION['message'] = "je bent ingelogd";
$_SESSION['username'] = $username;
$redirect = 'repairs.php';
break;
case '2':
$_SESSION['message'] = "je bent ingelogd";
$_SESSION['username'] = $username;
$redirect = 'lloverzicht.php';
break;
case '3':
$_SESSION['message'] = "je bent ingelogd";
$_SESSION['username'] = $username;
$redirect = 'overzicht.php';
break;
}
header('Location: '.$redirect);
}
}
它的代码基本相同,但它没有重定向到下一页。
我希望有人有建议或知道我做错了什么。
答案 0 :(得分:2)
首先,一些警告(in accordance with this link):
Little Bobby说 your script is at risk for SQL Injection Attacks. 了解prepared的MySQLi语句。即使escaping the string也不安全! Don't believe it?
你真的不应该使用MD5 password hashes ,你真的应该使用PHP的built-in functions来处理密码安全性。在散列之前,请确保don't escape passwords或使用任何其他清理机制。这样做更改密码并导致不必要的额外编码。
现在解决您的问题:
您需要从数据库中获取结果,以便定义$role
:
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result); // fetch the result of your query
$role = $row['role']; // assigned the value of $role
switch ($role) {
case '1':
$_SESSION['message'] = "je bent ingelogd";
$_SESSION['username'] = $username;
$redirect = 'repairs.php';
break;
case '2':
$_SESSION['message'] = "je bent ingelogd";
$_SESSION['username'] = $username;
$redirect = 'lloverzicht.php';
break;
case '3':
$_SESSION['message'] = "je bent ingelogd";
$_SESSION['username'] = $username;
$redirect = 'overzicht.php';
break;
}
header('Location: '.$redirect);
exit();
}
完成后,您需要在重定向后添加exit();
,以便PHP不会尝试处理重定向后您可能拥有的任何其他代码。