用 php 寫個網頁跳轉系統
Private research annotation
Sign in to add a private research label or note.
- User
用 php 寫個網頁跳轉系統
- Assistant
要寫一個網頁跳轉系統,可以使用 PHP 的
header函數。範例如下:
code<?php header('Location: http://www.example.com/'); exit; ?>這樣網頁就會跳轉到
http://www.example.com/。如果你想在幾秒之後再跳轉,可以使用 HTML 的
meta標籤,例如:code<meta http-equiv="refresh" content="5;URL='http://www.example.com/'" />這樣網頁就會在 5 秒後跳轉到
http://www.example.com/。請注意,使用
header函數時,你必須在發送任何輸出(包括空格和換行)之前呼叫它。否則,它將無法正常工作。 - User
幫我用 sqllite 儲存要跳轉的網頁,並幫我寫跳轉管理網頁
- Assistant
以下是使用 PHP 和 SQLite 儲存和管理網頁跳轉資訊的範例。
首先,你需要建立一個名為
redirects的 SQLite 資料庫,並在其中建立一個名為redirects的表,具有以下結構:codeCREATE TABLE redirects ( id INTEGER PRIMARY KEY, old_url TEXT NOT NULL, new_url TEXT NOT NULL );然後,你可以使用 PHP 的 PDO 擴展來連接到資料庫並執行 SQL 查詢。
建立跳轉:
code<?php // Connect to the database $db = new PDO('sqlite:redirects.db'); // Insert the redirect into the database $stmt = $db->prepare('INSERT INTO redirects (old_url, new_url) VALUES (?, ?)'); $stmt->execute(array($_POST['old_url'], $_POST['new_url'])); ?>顯示跳轉列表:
code - User
然後?
- Assistant
接下來,你可以將結果查詢存儲在變數中,並檢查是否找到了匹配的跳轉。如果找到了,則使用
header函數將瀏覽器重定向到新的 URL。code<?php // Connect to the database $db = new PDO('sqlite:redirects.db'); // Look up the redirect for the current URL $stmt = $db->prepare('SELECT * FROM redirects WHERE old_url = ?'); $stmt->execute(array($_SERVER['REQUEST_URI'])); $redirect = $stmt->fetch(); // Redirect to the new URL if a redirect was found if ($redirect) { header('Location: ' . $redirect['new_url']); exit; } ?>這樣,當用戶請求舊的 URL 時,他們將被重定向到新的 URL。
- User
那如何更新連結
- Assistant
要更新一個連結,你可以使用 SQLite 的
UPDATE語句,如下所示:code<?php // Connect to the database $db = new PDO('sqlite:redirects.db'); // Update the redirect $stmt = $db->prepare('UPDATE redirects SET old_url = ?, new_url = ? WHERE id = ?'); $stmt->execute(array($_POST['old_url'], $_POST['new_url'], $_POST['id'])); ?>你需要確保有一個表單,其中包含將更新的跳轉 ID,舊 URL 和新 URL。然後,在表單提交時,使用以上代碼更新跳轉。
注意:在執行
UPDATE語句之前,你可能需要驗證輸入的數據,以確保它是有效的。此外,如果你希望用戶能夠在跳轉管理網頁中直接更新跳轉,你可以使用 AJAX 技術或在表單中使用
PATCH請求來實現此功能。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.