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

PHP 網頁遊戲開發學習:Xnova (OGame) 源碼深度解讀(四)用戶登錄流程與會話管理

     編輯:PHP 相關知識

登錄入口:login.php 初始化

與註冊頁類似,但新增 LOGIN 常量與 $InLogin 變量:

define('INSIDE', true);
define('INSTALL', false);
define('LOGIN', true);
$InLogin = true;
$xnova_root_path = './';
include($xnova_root_path . 'extension.inc');
include($xnova_root_path . 'common.' . $phpEx);
includeLang('login');
  • LOGIN:標識登錄流程,影響 common.php 中的用戶檢查邏輯
  • $InLogin = true:告知公共代碼跳過自動登錄檢查

首次訪問:歡迎頁面數據準備

$parse = $lang;
// 總玩家數
$Count = doquery('SELECT COUNT(*) as `players` FROM {{table}} WHERE 1', 'users', true);
// 最後註冊玩家
$LastPlayer = doquery('SELECT `username` FROM {{table}} ORDER BY `register_time` DESC', 'users', true);
$parse['last_user'] = $LastPlayer['username'];
// 線上玩家數(15分鐘內活躍)
$PlayersOnline = doquery("SELECT COUNT(DISTINCT(id)) as `onlinenow` FROM {{table}} WHERE `onlinetime` > '" . (time()-900) ."';", 'users', true);
$parse['online_users'] = $PlayersOnline['onlinenow'];
$parse['users_amount'] = $Count['players'];
$parse['servername'] = $game_config['game_name'];
$parse['forum_url'] = $game_config['forum_url'];
$parse['PasswordLost'] = $lang['PasswordLost'];

$page = parsetemplate(gettemplate('login_body'), $parse);

// API 介面:獲取在線/總人數統計
if ($_GET['ucount'] == 1) {
    $page = $PlayersOnline['onlinenow'] . "/" . $Count['players'];
    die($page);
} else {
    display($page, $lang['Login']);
}

登錄驗證核心流程

  1. 查詢用戶記錄:根據用戶名從 game_users 獲取記錄
  2. 密碼驗證:md5($input_password) === $db_password
  3. 記住密碼處理:若勾選,設置長效 Cookie
  4. 載入配置:include config.php
  5. 設置 Cookie:寫入用戶名、加密密碼等標識
  6. 重定向:header('location: frames.php') 進入遊戲主界面

失敗分支調用 message() 輸出錯誤提示(用戶不存在、密碼錯誤、帳號被封禁等)。

Cookie 與會話機制深度剖析

Cookie 結構

典型設置:

setcookie('user', $username, time() + 31536000);  // 1年
setcookie('pass', $password_hash, time() + 31536000);

common.php 中的自動登錄檢查

當 $InLogin != true 時(即非登錄頁),執行:

$Result = CheckTheUser($IsUserChecked);
$IsUserChecked = $Result['state'];
$user = $Result['record'];

CheckTheUser() → CheckCookies()(定義於 includes/functions/CheckCookies.php)解析 Cookie、驗證密碼哈希、查詢用戶表、返回用戶數據陣列。

服務器關閉模式檢查

if ($InLogin == false) {
    if ($game_config['game_disable']) {
        if ($user['authlevel'] < 1) {
            message(stripslashes($game_config['close_reason']), $game_config['game_name']);
        }
    }
}

管理員(authlevel >= 1)維護期間仍可登錄,普通玩家見到維護公告。

安全隱患與改進方向

問題風險建議方案
MD5 密碼哈希 彩虹表攻擊、碰撞風險 遷移至 password_hash() / Argon2id
Cookie 存儲密碼哈希 XSS 竊取後可離線破解 改用 Session + HttpOnly Cookie,或 JWT
無 CSRF 保護 登錄表單可被偽造提交 增加 CSRF Token 驗證
無暴力破解防護 帳號枚舉、密碼噴灑攻擊 限制登錄頻率、CAPTCHA、帳號鎖定
SQL 拼接查詢 注入風險 全面採用 Prepared Statements

系列導航:第一部分 | 第二部分 | 第三部分 | 第四部分:用戶登錄 | 第五部分:主界面 | 第六部分:公共代碼

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