header("Location: ...") 會發送 302 重導向回應,瀏覽器收到後立即跳轉,不會執行先前輸出的 <script>alert(...)</script>。
移除 header(),改由前端腳本完成提示與跳轉:
<?php
session_start();
header("Content-type: text/html; charset=utf-8");
include("inc/conn.php");
if ($_SESSION['u_id'] == "") {
$from = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// 輸出 JavaScript 彈窗並跳轉
echo "<script>alert('請登錄後再使用!'); window.location.href='u_login.php?from=" . urlencode($from) . "';</script>";
exit; // 確保不再輸出後續內容
}
?>
window.location.href 實現客戶端跳轉,給予使用者閱讀彈窗的時間。urlencode($from) 處理 URL 參數特殊字元。exit 防止後續 PHP 程式碼輸出干擾。echo "<meta http-equiv='refresh' content='2;url=u_login.php?from=" . urlencode($from) . "'>";
echo "請登錄後再使用!2 秒後自動跳轉...";
但無法實現彈窗提示,體驗較差。
採用 JavaScript 方案即可同時達成「提示」與「跳轉」需求。