今天介紹和使用SESSION和撰寫登入、強制登入和保持登入狀態系統。
應用場景在網站具有會員登入的功能或是購物車的功能,基本上就會使用到 session ,這能來記錄你的資訊。
這適合用於存取暫時短暫的數據,如果想要長久的存取數據,數據庫和資料庫是更好的選擇。
session_start()
啟動session的東西,使用session前都要先使用這個一次。
session_destroy();
用於銷毀session中的全部數據
$_SESSION
存放一個值,以$_SESSION["名稱"]為變數。
範例:
$_SESSION["name"] = "alice";
接下來實作登出程式碼。
新增php檔(sign_out.php)在php資料夾中。
<?php
session_start();
session_destroy();
header('Location:/30days/message_board/screen/login.php');
用一個指令把session都清洗掉(就是這麼簡單)
以下之前寫過的程式碼中,有變動過的程式碼:
<?php
include("datatable.php");
if (isset($_POST["user_name"])) {
$_SESSION["user_name"] = $_POST["user_name"];
$_SESSION["password"] = $_POST["password"];
$user_name = $_SESSION["user_name"];
$password = $_POST["password"];
$account = check_password($user_name);
if (isset($account[0]['user_name'])) {
if (($account[0]['user_name'] == $user_name) && ($account[0]['password'] == $password)) {
$_SESSION["user_name"] = $user_name;
header('Location:/30days/message_board/screen/Home.php');
} else {
echo "<script>alert('密碼錯誤');</script>" . "<br>";
echo "密碼錯誤" . "<br>";
}
} else {
echo "<script>alert('此帳號沒有註冊');</script>" . "<br>";
echo "此帳號沒有註冊" . "<br>";
header('Location:/30days/message_board/screen/register.php');
}
}
登入時檢測密碼後,如果確認通過,就會把名稱記錄到session。
<!DOCTYPE html>
<html lang="en">
<?php
include("../php/datatable.php");
if (!(isset($_SESSION["user_name"]))) {
header('Location:/30days/message_board/screen/login.php');
}
$comments = getAllComments();
?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<title>留言板</title>
</head>
<body>
<ul class="nav nav-tabs justify-content-center">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="Home.php">留言板</a>
</li>
<li class="nav-item">
<a class="nav-link" href="register.php">註冊</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../php/sign_out.php">登出</a>
</li>
</ul>
<div class="mb-5 pb-5">
<h1 class="text-center">留言板</h1>
<div class="mx-5 mt-5">
<form method="POST" action="../php/create_comment.php">
<p class="input-group-text text-light bg-dark">
暱稱:<?php echo $_SESSION["user_name"]; ?>
</p>
<div class="">
<div class="input-group-prepend">
<span class="input-group-text text-light bg-dark">評論: </span>
</div>
<textarea class="form-control" name="comment" required="required" cols="40" rows="5" placeholder="輸入評論"></textarea>
</div>
<input type="hidden" name="id" value="id">
<input type="submit" name="submit" class="btn btn-dark" value="新增資料" style="float:left">
</form>
</div>
</div>
<div>
<h2 class="mt-4 text-center">留言:</h2>
<?php
// echo var_dump($comments);
foreach ($comments as $row) {
?>
<div class="mx-3 my-3">
<h5 class="mx-3 mt-2"><?php echo $row["name"]; ?></h5>
<p class="mx-3"><?php echo $row["comment"]; ?></p>
<div>
<a href="../php/edit_comment.php?id=<?php echo $row['id'] ?>">
<input type="submit" value="修改" class="btn btn-dark mx-3" style="float:right">
</a>
<form method="POST" action="../php/delete_comment.php">
<input type="hidden" name="id" value="<?php echo $row['id'] ?>">
<input type="submit" value="刪除" class="btn btn-danger" style="float:right">
</form>
</div>
</div>
<?php
}
?>
</div>
</body>
</html>
改為登入名稱為留言者名稱,並會顯示留言者名稱在新增留言的畫面。
另外增加如果沒有登入,從登入網址進入會跳轉頁面如影片所示。
通過檢測session有沒有存放name,來確認,一旦有就能直接進入,無須登入,保持登入狀態(所以會出現忘了登出的情況)。
<html>
<head>
<meta charset="UTF-8">
<title>Guestbook</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body style="background-color:F0F0F0;">
<div class="mt-5">
<h1 class="mt-4 text-center">編輯留言</h1>
<div class="p-3">
<form method="POST" action="../php/update_comment.php">
<?php echo "<p class=\"input-group-text text-light bg-dark\">" . "暱稱:" . $_SESSION["user_name"] . "</p>" ?>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text text-light bg-dark">評論: </span>
</div>
<textarea class="form-control" name="comment" required="required" cols="40" rows="5" placeholder="輸入評論"></textarea>
</div>
<input type="hidden" name="id" value="<?php echo $id ?>"><!-- //?? -->
<input type="submit" name="submit" class="btn btn-dark" value="修改資料">
</form>
</div>
</div>
<!-- <p><?php echo json_encode($statement[0]['comment']); ?></p> -->
</body>
</html>
和留言板相同,會顯示留言者名稱在修改留言的畫面。
<?php
include("datatable.php");
$comment = $_POST['comment'];
$statement = createComment($comment);
header('Location:/30days/message_board/screen/Home.php');
留言者名稱不在用Post來讀取,而是用session,所以可省略刪除程式碼。
<?php
session_start();
function dbConnect() //連接資料庫
{
$db_type = 'mysql';
$db_host = 'localhost';
$db_name = 'messageboard_ithome';
$db_user = 'root';
$db_password = '';
$dbconnect = "mysql:host=" . $db_host . ";dbname=" . $db_name;
$db = new PDO($dbconnect, $db_user, $db_password);
$db->query("SET NAMES UTF8");
return $db;
}
function register_account($user_name, $password) //註冊帳號
{
$db = dbConnect();
$statement = $db->prepare("INSERT INTO account(user_name, password) VALUES(?,?)");
$statement->execute([$user_name, $password]);
return $statement;
}
function check_password($user_name)
{
$db = dbConnect();
$account = $db->prepare("SELECT user_name,password FROM account WHERE user_name=?");
$account->execute([$user_name]);
return $account->fetchAll(PDO::FETCH_ASSOC);
}
function createComment($comment)
{
$db = dbConnect();
$name = $_SESSION["user_name"];
$statement = $db->prepare("INSERT INTO messageboard(name,comment) VALUES(?,?)");
$statement->execute([$name, $comment]);
return $statement;
}
function getAllComments()
{
$db = dbConnect();
$statement = $db->prepare("SELECT *FROM messageboard");
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
function deleteComment($id)
{
$db = dbConnect();
$statement = $db->prepare("DELETE FROM messageboard WHERE id= ?");
$statement->execute([$id]);
return $statement;
}
function editComment($id)
{
$db = dbConnect();
$statement = $db->prepare("SELECT *FROM messageboard WHERE id=?");
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
function updateComment($id, $comment)
{
$db = dbConnect();
$statement = $db->prepare("UPDATE messageboard SET COMMENT=? WHERE id=?");
$statement->execute([$comment, $id]);
return $statement;
}
創建留言時,留言者的名稱為登入時的名稱,也就登入驗證時所記錄的session。