config.php 定義 Session 鍵名常數config.php<?php
return [
// 資料庫設定
'DB_TYPE' => 'mysql',
'DB_HOST' => 'localhost',
'DB_NAME' => 'myuser',
'DB_USER' => 'root',
'DB_PWD' => '',
'DB_PORT' => '3306',
'DB_PREFIX' => 'think_',
// 登入 Session 鍵名
'USER_AUTH_KEY' => 'authId',
];
AdminAction::insert()public function insert() {
header('Content-Type: text/html; charset=utf-8');
$user = $_POST['user'];
$this->verifyCheck(); // 驗證碼檢查
$model = D('user');
$data = $model->create();
if (!$data) $this->error($model->getError());
$uid = $model->add(); // 回傳新增 ID
if ($uid) {
// 關鍵:寫入 Session
Session::set(C('USER_AUTH_KEY'), $user);
$this->success('註冊成功', 'index/index');
} else {
$this->error('註冊失敗');
}
}
IndexAction::index()public function index() {
if (!Session::is_set(C('USER_AUTH_KEY'))) {
$msg = '用戶未登入';
} else {
$msg = Session::get(C('USER_AUTH_KEY')) . ' 歡迎回來';
}
$this->assign('msg', $msg);
$this->display();
}
index.html<body>
{$msg}<br/>
這是我的首頁
</body>
| 操作 | 方法 |
|---|---|
| 寫入 | Session::set(C('USER_AUTH_KEY'), $value) |
| 判斷存在 | Session::is_set(C('USER_AUTH_KEY')) |
| 讀取 | Session::get(C('USER_AUTH_KEY')) |
| 刪除 | Session::delete(C('USER_AUTH_KEY')) |
password_hash() 加密儲存,驗證用 password_verify()session_regenerate_id(true) 防 Session FixationThinkPHP 3.2 版本語法示範,新版(5.0/6.0/8.0)請參考官方文件對應 session() 助手函數或 think\Session 門面。