以 **Session** 為儲存後端 (無資料庫),示範登入驗證、學生資料 CRUD (新增、列表、查詢、畢業/刪除、更新)、關鍵字搜尋等核心功能。適合教學、原型驗證或輕量內部工具。
<?php
session_start();
$user = $_POST['userName'] ?? '';
$pass = $_POST['passWord'] ?? '';
if ($user === 'Admin' && $pass === 'root') {
$_SESSION['user'] = $user;
setcookie('userName', $user, time() + 1200, '/', '', false, true); // HttpOnly
header('Location: main.php');
exit;
}
header('Location: index.php?error=1');
exit;
?>
<?php
session_start();
if (empty($_SESSION['user'])) { header('Location: index.php'); exit; }
$id = trim($_POST['s_ID'] ?? '');
$name = trim($_POST['Name'] ?? '');
$idCard = trim($_POST['IDcard'] ?? '');
$major = trim($_POST['Major'] ?? '');
$sex = trim($_POST['sex'] ?? '');
if ($id && $name) {
$_SESSION['students'][$id] = [
's_ID' => $id,
'Name' => $name,
'IDcard' => $idCard,
'Major' => $major,
'sex' => $sex,
];
}
header('Location: main.php?msg=added');
exit;
?>
<?php
session_start();
if (empty($_SESSION['user'])) { header('Location: index.php'); exit; }
$students = $_SESSION['students'] ?? [];
?>
學生列表
學生列表 (共 =count($students)?> 筆)
學號 姓名 身份證號 性別 專業 操作
=$stu['s_ID']?>
=$stu['Name']?>
=$stu['IDcard']?>
=$stu['sex']?>
=$stu['Major']?>
編輯 |
畢業
回主頁
<?php
session_start();
if (empty($_SESSION['user'])) { header('Location: index.php'); exit; }
$kw = trim($_POST['search'] ?? '');
$results = [];
if ($kw) {
foreach ($_SESSION['students'] as $stu) {
if (in_array($kw, $stu, true)) { // 搜尋所有欄位
$results[$stu['s_ID']] = $stu;
}
}
}
$_SESSION['search_results'] = $results;
header('Location: search_result.php');
exit;
?>
<?php
session_start();
if (empty($_SESSION['user'])) { header('Location: index.php'); exit; }
$id = $_GET['id'] ?? '';
if ($id && isset($_SESSION['students'][$id])) {
// 移至歷史檔 (示範)
$_SESSION['history'][$id] = $_SESSION['students'][$id];
unset($_SESSION['students'][$id]);
}
header('Location: list.php');
exit;
?>
<!-- edit.php -->
<?php
session_start();
if (empty($_SESSION['user'])) { header('Location: index.php'); exit; }
$id = $_GET['id'] ?? '';
$stu = $_SESSION['students'][$id] ?? null;
if (!$stu) { header('Location: list.php'); exit; }
?>
<!-- update.php -->
<?php
session_start();
if (empty($_SESSION['user'])) { header('Location: index.php'); exit; }
$id = $_POST['c_ID'] ?? '';
if ($id && isset($_SESSION['students'][$id])) {
$_SESSION['students'][$id] = array_merge($_SESSION['students'][$id], [
'Name' => $_POST['Name'] ?? '',
'Major' => $_POST['Major'] ?? '',
'sex' => $_POST['sex'] ?? '',
]);
}
header('Location: list.php');
exit;
?>
<?php
session_start();
if (empty($_SESSION['user'])) { header('Location: index.php'); exit; }
?>
管理主頁
歡迎 =htmlspecialchars($_SESSION['user'])?> (Cookie 1200 秒)
此簡易系統展示 PHP Session 應用、MVC 雛形與基本 CRUD 流程,可作為進一步開發的起點。