用 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語句來更新現有的跳轉記錄。例如,你可以使用以下程式碼來更新舊的 URL 為新的 URL:
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'])); ?>你可以在網頁中使用 HTML 表單來讓用戶輸入新的跳轉訊息,然後使用 PHP 來更新資料庫。
範例 HTML 表單:
code<form method="post" action="/update-redirect.php"> <label for="old_url">Old URL:</label> <input type="text" id="old_url" name="old_url" value="<?php echo htmlspecialchars($redirect['old_url']) ?>" /> <br /> <label for="new_url">New URL:</label> <input type="text" id="new_url" name="new_url" value="<?php echo htmlspecialchars($redirect['new_url']) ?>" /> <br /> <input type="hidden" name="id" value="<?php echo htmlspecialchars($redirect['id']) ?>" /> <input type="submit" value="Update redirect" /> </form>
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.