當您通過我的登錄表單登錄時,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
好的!虐待使用,在未來:-) –