function alert(string $message, string $url = '', bool $isAlert = true, string $title = '提示') : void
<?php
/**
* 輸出 HTML + JavaScript 彈窗並跳轉
* @param string $message 提示訊息
* @param string $url 跳轉目標:空字串=history.back(),完整 URL=location.href
* @param bool $isAlert 是否顯示 alert 彈窗
* @param string $title 頁面 title
* @return void 直接 exit
*/
function alert($message, $url = '', $isAlert = true, $title = '提示') {
// 1. 輸出基本 HTML 骨架
echo '<html><head>';
echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
echo '<title>' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</title>';
echo '</head><body>';
// 2. 輸出 JS 邏輯
echo '<script type="text/javascript">';
if ($isAlert) {
// 轉義單引號防止 JS 語法錯誤
$safeMsg = str_replace("'", "\\'", $message);
echo "alert('$safeMsg');";
}
if ($url === '') {
echo "history.back();";
} else {
$safeUrl = str_replace("'", "\\'", $url);
echo "location.href='$safeUrl';";
}
echo '</script>';
echo '</body></html>';
exit;
}
?>
| 場景 | 呼叫方式 | 行為 |
|---|---|---|
| 表單驗證失敗,返回上頁 | alert('手機格式錯誤'); | 彈窗 → history.back() |
| 刪除成功,跳轉列表頁 | alert('刪除成功', '/admin/user/list'); | 彈窗 → location.href |
| 僅跳轉不彈窗(如登入攔截) | alert('', '/login', false); | 無彈窗 → 直接跳轉 |
| 自訂標題 | alert('權限不足', '', true, '錯誤'); | 標題顯示「錯誤」 |
<?php
function alert_safe($message, $url = '', $isAlert = true, $title = '提示') {
// 只允許相對路徑或同域絕對路徑
if ($url !== '' && !preg_match('#^(/|https?://' . preg_quote($_SERVER['HTTP_HOST'], '#') . ')#', $url)) {
$url = '/';
}
// 訊息長度限制
$message = mb_substr($message, 0, 500, 'UTF-8');
alert($message, $url, $isAlert, $title);
}
?>
{msg: '', url: ''} 自行處理彈窗(SweetAlert2、Layer、Toast)return redirect()->back()->with('error', '訊息'); 配合 Blade 模板顯示傳統 alert() 適合快速原型、純後端渲染專案、維護舊系統;新專案建議採用前後端分離模式。