Web 開發中頻繁需要「操作成功/失敗 → 提示信息 → 延遲跳轉」的交互模式。本文提供一個參數化的 redirect() 函數與單例模式的 Tips 提示類,覆蓋 HTML Meta、HTTP Header、JavaScript 三種跳轉方式。
/**
* 瀏覽器重定向綜合函數
* @param string $url 目標 URL
* @param int $delay 延遲秒數 (0 立即)
* @param bool $js 是否返回 JS 代碼而非直接執行
* @param bool $jsWrapped JS 代碼是否包裝在 ';
if ($return) return $out;
echo $out;
exit;
}
redirect('/list.php'):立即 302 跳轉redirect('/list.php', 3):3 秒後 Meta Refreshredirect('/list.php', 0, true, true, true):獲取 <script>document.location='...'</script> 字符串供 AJAX 返回redirect('/list.php', 2, true, false, true):獲取純 JS 代碼 window.setTimeout(...) 嵌入頁面class Tips {
private $tips;
static private $_instance;
private function __construct($string, $url) {
$this->tips = "
{$string}
返回 (4秒後自動跳轉)";
}
public function __toString() { return $this->tips; }
private function __clone() {}
public static function get_tips($string, $url) {
if (!(self::$_instance instanceof self)) {
self::$_instance = new self($string, $url);
}
return self::$_instance;
}
}
require_once 'tips_class.php'; $msg = "錯誤:兩次輸入的密碼不一致"; $url = "../login.php"; echo Tips::get_tips($msg, $url); // __toString() 自動輸出
echo $obj 即可輸出 HTML,極致簡潔。redirect() 覆蓋所有常見跳轉場景,消除項目中散落的跳轉邏輯。Cannot modify header information 警告。