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

PHP Cookie 完整應用實戰:登入狀態管理與資料讀取

     編輯:PHP 綜合知識

Cookie 機制在 PHP 登入系統中的實作

Cookie 是維持 HTTP 無狀態協定下用戶會話的常用手段。本文示範完整的登入/登出流程:設定 Cookie、加密驗證、登入狀態檢查、銷毀 Cookie,並搭配資料庫讀取顯示用戶資料。

1. 登入時設定 Cookie

// 登入驗證通過後
_setcookies($_rows['tg_username'], $_rows['tg_uniqid'], $_clean['time']);
_location(null, 'index.php');

2. Cookie 設定函式(支援多種有效期)

function _setcookies($_username, $_uniqid, $_time) {
    setcookie('username', $_username);
    setcookie('uniqid', $_uniqid);

    switch ($_time) {
        case '0':  // 瀏覽器進程(關閉瀏覽器失效)
            setcookie('username', $_username);
            setcookie('uniqid', $_uniqid);
            break;
        case '1':  // 1 天
            setcookie('username', $_username, time() + 86400);
            setcookie('uniqid', $_uniqid, time() + 86400);
            break;
        case '2':  // 1 週
            setcookie('username', $_username, time() + 604800);
            setcookie('uniqid', $_uniqid, time() + 604800);
            break;
        case '3':  // 1 月(原碼 case 0 重複,這裡修正為 3)
            setcookie('username', $_username, time() + 2592000);
            setcookie('uniqid', $_uniqid, time() + 2592000);
            break;
    }
}

注意:原始碼中 `case '0'` 出現兩次,最後一個應為 `case '3'` 代表一個月。

3. 登入狀態驗證與登出銷毀

// 檢查登入狀態
function _login_state() {
    if (!isset($_COOKIE['username'])) {
        _alert_back("登入狀態無法進行本操作!");
    }
}

// 登出:銷毀 Cookie 與 Session
function _unsetcookies() {
    setcookie('username', '', time() - 1);
    setcookie('uniqid', '', time() - 1);
    _session_destroy();
    _location(null, 'index.php');
}

// 需驗證的頁面引入
_login_state();

4. 資料庫封裝與資料讀取顯示

// 單筆查詢
function _fetch_array($_sql) {
    return mysql_fetch_array(_query($_sql), MYSQL_ASSOC);
}

// 多筆查詢(回傳結果集資源,需迴圈處理)
function _fetch_array_list($_result) {
    return mysql_fetch_array($_result, MYSQL_ASSOC);
}

// 使用範例
$_result = _query("SELECT tg_username, tg_sex, tg_face FROM tg_user ORDER BY tg_reg_time DESC");
while (!!$_rows = _fetch_array_list($_result)) {
    echo '<dd class="user">' . $_rows['tg_username'] . $_rows['tg_sex'] . '</dd>';
    echo '<dt><img src="' . $_rows['tg_face'] . '" alt="" /></dt>';
}

安全性建議

  1. 加密唯一標識:`uniqid` 應為加密雜湊值(如 `md5(密碼 . 隨機鹽)`),避免直接儲存明文密碼
  2. HttpOnly 旗標:`setcookie(..., true)` 防止 XSS 竊取 Cookie
  3. Secure 旗標:HTTPS 環境下啟用,確保 Cookie 僅在加密傳輸
  4. SameSite 屬性:設為 `Lax` 或 `Strict` 防禦 CSRF 攻擊
  5. 資料庫擴展:範例使用已棄用的 `mysql_*` 函式,生產環境請改用 PDO 或 MySQLi 預處理語句

完善的 Cookie 管理是會話控制的基礎,結合 Session、資料庫驗證可構建安全可靠的認證系統。

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