這是一段約 2000 年左右的 PHP3 歷史代碼片段,展示了早期 PHP 開發的風格:.php3 副檔名、$HTTP_COOKIE_VARS、$GLOBALS['PHP_SELF']、MySQL_query (大小寫不敏感)、手動拼接 SQL、setcookie 無 httponly/secure 參數。僅供歷史參考與教學對比,**絕不可用於現代專案**。
<?php
require("/commonfuncs.php3");
require("home/websrc/userfuncs.php3");
function makeloginform() {
echo "Please login first\n";
}
echo $GLOBALS["PHP_SELF"];
if (!$HTTP_COOKIE_VARS["UserID"]) {
if (!$UserName) { // register_globals=On 時代產物
makeloginform();
exit;
}
if (!$userinfo = getuserbyname($UserName)) {
echo "Login Name Error!";
exit;
}
if ($userinfo->password != $Password) { // 明文密碼比對!
echo "Login Password Error!";
exit;
}
$conn = DBConnect();
$sql = "insert into useronline(uid,logintime,username) values(";
$sql .= $userinfo->name; // 直接拼接,SQL 注入高風險
$sql .= "')";
mysql_query($sql, $conn); // 拼寫錯誤:mysql_query vs MySQL_query
DBClose($conn);
if (!(setcookie("UserID", $userinfo->id, "", "/"))) { // 無 httponly, secure, samesite
echo "Set Cookie Error!!";
exit;
}
$strHeader = "Location: " . $PHP_SELF;
header($strHeader);
exit;
}
?>
| 特徵 | PHP3/4 時代寫法 | 現代 PHP (8.x) 寫法 |
|---|---|---|
| 副檔名 | .php3 / .php4 | .php |
| 超全域變數 | $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_SERVER_VARS | $_GET, $_POST, $_COOKIE, $_SERVER |
| Register Globals | 預設 On (極度危險) | PHP 5.4 移除,永遠 Off |
| 資料庫擴充 | mysql_* (PHP 7.0 移除) | PDO / mysqli (預處理語句) |
| 密碼儲存 | 明文或簡單 MD5 | password_hash() (Bcrypt/Argon2id) |
| Cookie 安全 | setcookie(name, value, expire, path) | setcookie(name, value, ['expire'=>..., 'path'=>'/', 'secure'=>true, 'httponly'=>true, 'samesite'=>'Lax']) |
| SQL 組裝 | 字串拼接 | 參數化查詢 / ORM / Query Builder |
| 錯誤處理 | die/exit + echo | Exception / Throwable + 統一錯誤處理器 |
| 編碼 | Big5 / GB2312 常見 | UTF-8 (mbstring 內建) |
<?php
declare(strict_types=1);
require_once __DIR__ . '/../config/database.php'; // PDO 實例 $pdo
require_once __DIR__ . '/../src/AuthService.php';
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
if ($username === '' || $password === '') {
throw new InvalidArgumentException('帳號密碼不可為空');
}
$stmt = $pdo->prepare('SELECT id, username, password_hash FROM users WHERE username = ? LIMIT 1');
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password_hash'])) {
// 登入成功
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
// 記錄登入日誌 (預處理)
$logStmt = $pdo->prepare('INSERT INTO user_logins (user_id, ip, ua, created_at) VALUES (?, ?, ?, NOW())');
$logStmt->execute([$user['id'], $_SERVER['REMOTE_ADDR'] ?? '', $_SERVER['HTTP_USER_AGENT'] ?? '']);
// 安全 Cookie
setcookie('session_id', session_id(), [
'expires' => time() + 3600*24*30,
'path' => '/',
'domain' => '', // 當前域名
'secure' => true, // 僅 HTTPS
'httponly' => true, // JS 不可讀
'samesite' => 'Lax',
]);
header('Location: /dashboard');
exit;
}
// 失敗:統一訊息防止用戶枚舉
$error = '帳號或密碼錯誤';
}
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>登入</title></head><body>
<h1>登入</h1>
<?php if (!empty($error)): ?><p style="color:red"><?= htmlspecialchars($error) ?></p><?php endif; ?>
<form method="post">
<label>帳號: <input name="username" required></label><br>
<label>密碼: <input name="password" type="password" required></label><br>
<button type="submit">登入</button>
</form>
</body></html>