會員制網站常見需求:使用者存取需登入的頁面 → 導向登入頁 → 登入成功 → 跳回原頁。本文提供 Cookie 法與 GET 參數法兩種方案完整實作。
<?php
// BaseController.php
class BaseController {
protected function initialize() {
// 排除登入、註冊、靜態資源等頁面
$excluded = ['login', 'register', 'logout', 'captcha'];
$currentAction = request()->action();
if (!in_array($currentAction, $excluded) && !request()->isAjax()) {
// 儲存完整 URL 到 Cookie (加密更安全)
$referer = url()->current(); // 或 $_SERVER['REQUEST_URI']
Cookie::set('redirect_after_login', $referer, 3600); // 1小時有效
}
}
}
?>
<?php
// AuthController.php
public function login() {
if (request()->isPost()) {
$credentials = request()->only(['username', 'password']);
if (Auth::attempt($credentials)) {
// 登入成功,取得儲存的跳轉目標
$redirectUrl = Cookie::get('redirect_after_login');
Cookie::delete('redirect_after_login'); // 用完即刪
// 安全驗證:防止開放重導向攻擊
$redirectUrl = $this->validateRedirectUrl($redirectUrl);
// AJAX 請求回傳 JSON,一般請求直接跳轉
if (request()->isAjax()) {
return json(['code' => 1, 'url' => $redirectUrl]);
}
return redirect($redirectUrl);
}
return json(['code' => 0, 'msg' => '帳號或密碼錯誤']);
}
return view('login');
}
private function validateRedirectUrl(?string $url): string {
if (empty($url)) return url('/dashboard'); // 預設首頁
// 解析 URL
$parsed = parse_url($url);
// 僅允許相對路徑或同域名
if (isset($parsed['host']) && $parsed['host'] !== request()->host()) {
return url('/dashboard');
}
// 防止 javascript:、data: 等危險協議
if (preg_match('/^(javascript|data|vbscript):/i', $url)) {
return url('/dashboard');
}
return $url;
}
?>
<?php
// Middleware / Filter
public function handle($request, Closure $next) {
if (Auth::guest() && !$this->isPublicRoute($request)) {
// 建立帶 redirect 參數的登入 URL
$loginUrl = url('login') . '?redirect=' . urlencode($request->fullUrl());
return redirect($loginUrl);
}
return $next($request);
}
?>
<!-- login.blade.php -->
<form method="POST" action="{{ url('login') }}">
@csrf
<input type="hidden" name="redirect" value="{{ request('redirect') }}">
<div><input name="email" type="email" placeholder="信箱"></div>
<div><input name="password" type="password" placeholder="密碼"></div>
<button type="submit">登入</button>
</form>
<?php
public function authenticate() {
$credentials = request()->only('email', 'password');
$redirect = request('redirect', '/dashboard');
if (Auth::attempt($credentials)) {
$redirect = $this->validateRedirectUrl($redirect);
return redirect($redirect);
}
// 失敗時保留 redirect 參數重新顯示表單
return back()->withInput()->with('redirect', $redirect);
}
?>
| 特性 | Cookie 方案 | GET 參數方案 |
|---|---|---|
| URL 乾淨度 | ✅ 乾淨 | ❌ 帶參數 |
| 多頁籤支援 | ❌ 共用 Cookie 會互相干擾 | ✅ 各分頁獨立 |
| 安全性 | 需防開放重導向、加密 Cookie | 需驗證 redirect 參數合法性 |
| 靜態快取相容 | ✅ 不影響頁面快取 | ❌ URL 不同導致快取分裂 |
| 實作複雜度 | 中 (需基礎控制器) | 低 (單點處理) |
<?php
function validateRedirectUrl(?string $url, string $default = '/'): string {
if (empty($url)) return $default;
$parsed = parse_url($url);
// 1. 禁止外部域名
if (isset($parsed['host']) && $parsed['host'] !== $_SERVER['HTTP_HOST']) {
return $default;
}
// 2. 禁止危險協議
if (preg_match('/^(javascript|data|vbscript|file):/i', $url)) {
return $default;
}
// 3. 可選:僅允許白名單路徑
$allowedPrefixes = ['/dashboard', '/profile', '/orders', '/settings'];
$path = $parsed['path'] ?? '/';
if (!empty($allowedPrefixes)) {
$allowed = false;
foreach ($allowedPrefixes as $prefix) {
if (str_starts_with($path, $prefix)) { $allowed = true; break; }
}
if (!$allowed) return $default;
}
return $url;
}
?>
<?php
// API 回傳跳轉資訊,前端 router 處理跳轉
public function loginApi() {
if (Auth::attempt(request()->only('email', 'password'))) {
$redirect = $this->validateRedirectUrl(
Cookie::pull('redirect_after_login') ?? request('redirect')
);
return response()->json([
'code' => 200,
'message' => '登入成功',
'redirect' => $redirect,
'token' => Auth::user()->createToken('api')->plainTextToken,
]);
}
return response()->json(['code' => 401, 'message' => '認證失敗'], 401);
}
?>