首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

ThinkPHP 登入功能實作:Session 管理、註冊自動登入與模板顯示

     編輯:PHP 綜合知識

核心流程

  1. 設定 config.php 定義 Session 鍵名常數
  2. 註冊成功後寫入 Session
  3. 首頁判斷 Session 顯示歡迎訊息
  4. 模板輸出變數

1. 設定檔 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',
];

2. 註冊動作 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('註冊失敗');
    }
}

3. 首頁判斷 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();
}

4. 模板 index.html

<body>
    {$msg}<br/>
    這是我的首頁
</body>

Session 操作速查

操作方法
寫入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 ID:session_regenerate_id(true) 防 Session Fixation
  • 重要操作需二次驗證(簡訊、郵件、TOTP)
  • Session 儲存建議改用 Redis(多伺服器共享、持久化)

ThinkPHP 3.2 版本語法示範,新版(5.0/6.0/8.0)請參考官方文件對應 session() 助手函數或 think\Session 門面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved