当您通过我的登录表单登录时,authentication.php将检查来自输入的数据是否在数据库中存在。当有匹配时,用户将被定向到他的角色的页面,因此可以说用户是管理员,他将被引导到admin.php。当用户成功登录时,我想显示欢迎名字姓氏等消息。在我的数据库中,我有一个名为firstname的字段和一个名为lastname的字段。我希望有人能帮助我这个,因为我似乎无法弄清楚:(根据会话从数据库获取数据
authentication.php
<?php
session_start();
// Making a connection with the database.
$mysqli=new MySQLi("localhost", "root", "root", "portfolio");
$role="";
// Declaring the username and password input.
$username=filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password=filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
// If role from members where username and password from inputs exicts in database bind parameters.
// If given parameters not excists in database die
if($query=$mysqli->prepare("SELECT `role` FROM members WHERE username=? AND password=?")) {
$query->bind_param("ss", $username, $password);
$query->execute();
$query->bind_result($role);
$query->fetch();
} else {
echo "Errors in the Query. ".$mysqli->error;
die();
}
// If $role is filled make session for username to check if logged in and session role for redirect page.
// If $role and $username is not filled invalid password, username combination.
if($role!="") {
$_SESSION['ingelogt']=$username;
$_SESSION['user_role']=$role;
$location="$role.php";
header("location: $location");
} else {
echo "Invalid password, username combination";
echo "<br/><a href='login.html'>Click to go back</a>";
}
?>
页的管理员将被引导到被称为admin.php的
<?php
session_start();
// If session is not ingelogt lead back to index.php.
if(!isset($_SESSION['ingelogt'])) {
header("location: index.php");
}
// The role that has access to this page.
$page_role="admin";
$role=$_SESSION['user_role'];
// If a user with a different role visits wrong page.
if($role!=$page_role)
{
echo "You are not supposed to be here.";
die();
}
// Start new DOMDocument and load html file.
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile("admin.html");
libxml_use_internal_errors(false);
// If user is logged in add logg out icon in the menu.
if($_SESSION['ingelogt']) {
$oUl = $dom->getElementById('navUl');
$oList = $dom->createElement('li');
$oLink = $dom->createElement('a');
$oLink->setAttribute('href','logout.php');
$oI = $dom->createElement('i');
$oI->setAttribute('class','icon-logout');
$oLink->appendChild($oI);
$oList->appendChild($oLink);
$oUl->appendChild($oList);
}
// Save DOMDocument with html document.
echo $dom->saveHTML();
?>
请注意,客户端可能会在HTTP响应中跳过一个Location信头......这只是“请求”浏览器重定向的一种方式,但这并不意味着他们必须“听”。如果要确保用户无法通过代码中的那一点,请始终在'header(“Location:some_uri”)'后面使用'die()'或'exit()''。 – Max
好的!虐待使用,在未来:-) –