Cookie 是維持 HTTP 無狀態協定下用戶會話的常用手段。本文示範完整的登入/登出流程:設定 Cookie、加密驗證、登入狀態檢查、銷毀 Cookie,並搭配資料庫讀取顯示用戶資料。
// 登入驗證通過後 _setcookies($_rows['tg_username'], $_rows['tg_uniqid'], $_clean['time']); _location(null, 'index.php');
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'` 代表一個月。
// 檢查登入狀態
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();
// 單筆查詢
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>';
}
完善的 Cookie 管理是會話控制的基礎,結合 Session、資料庫驗證可構建安全可靠的認證系統。