萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 整合多搜尋引擎跳轉:關鍵字導向 Google、Yahoo、百度實作

需求場景

建立一個統一搜尋入口,使用者輸入關鍵字並選擇搜尋引擎,PHP 後端根據選擇導向對應引擎的搜尋結果頁。適合:站內搜尋整合、多引擎比對工具、SEO 研究工具。

核心實現代碼

<?php
// search.php - 統一搜尋跳轉入口

// 1. 獲取並驗證參數
$keyword = trim($_GET['keyword'] ?? $_POST['keyword'] ?? '');
$engine  = strtolower(trim($_GET['engine'] ?? $_POST['engine'] ?? 'google'));

// 安全:限制允許的引擎白名單
$allowedEngines = ['google', 'bing', 'yahoo', 'duckduckgo', 'baidu', 'sogou', '360'];
if (!in_array($engine, $allowedEngines, true)) {
    $engine = 'google'; // 預設回退
}

// 關鍵字編碼:URL 編碼防注入
$encodedKeyword = urlencode($keyword);

// 2. 構建目標 URL 映射表
$engineUrls = [
    'google'      => "https://www.google.com/search?q={$encodedKeyword}",
    'bing'        => "https://www.bing.com/search?q={$encodedKeyword}",
    'yahoo'       => "https://search.yahoo.com/search?p={$encodedKeyword}",
    'duckduckgo'  => "https://duckduckgo.com/?q={$encodedKeyword}",
    'baidu'       => "https://www.baidu.com/s?wd={$encodedKeyword}",
    'sogou'       => "https://www.sogou.com/web?query={$encodedKeyword}",
    '360'         => "https://www.so.com/s?q={$encodedKeyword}",
];

$targetUrl = $engineUrls[$engine] ?? $engineUrls['google'];

// 3. 執行跳轉(302 臨時重導向)
// 使用 header() 必須在任何輸出之前
header("Location: {$targetUrl}", true, 302);
exit(); // 關鍵:阻止後續代碼執行
?>

前端表單範例 (HTML5)

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>多引擎統一搜尋</title>
    <style>
        body {font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; max-width: 600px; margin: 50px auto; padding: 0 20px;}
        .search-box {display: flex; gap: 10px; margin-bottom: 20px;}
        .search-box input[type="text"] {flex: 1; padding: 12px; font-size: 16px; border: 2px solid #ddd; border-radius: 4px;}
        .search-box select {padding: 12px; font-size: 16px; border: 2px solid #ddd; border-radius: 4px; background: white;}
        .search-box button {padding: 12px 24px; font-size: 16px; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer;}
        .search-box button:hover {background: #3367d6;}
        .engine-logos {display: flex; gap: 15px; opacity: 0.6; font-size: 14px; color: #666;}
    </style>
</head>
<body>
    <h1>🔍 多引擎統一搜尋</h1>
    
    <form action="search.php" method="GET" class="search-box">
        <input type="text" name="keyword" placeholder="輸入搜尋關鍵字..." required autocomplete="off">
        <select name="engine">
            <option value="google">🌐 Google</option>
            <option value="bing">🔷 Bing</option>
            <option value="yahoo">🟣 Yahoo</option>
            <option value="duckduckgo">🦆 DuckDuckGo</option>
            <option value="baidu">🔴 百度</option>
            <option value="sogou">🟢 搜狗</option>
            <option value="360">🔵 360搜尋</option>
        </select>
        <button type="submit">搜尋</button>
    </form>
    
    <div class="engine-logos">
        <span>支援引擎:Google、Bing、Yahoo、DuckDuckGo、百度、搜狗、360</span>
    </div>
</body>
</html>

進階功能擴展

1. AJAX 無刷新獲取結果(跨域限制需後端代理)

<?php
// api/search_proxy.php - 後端代理解決跨域
$engine = $_GET['engine'] ?? 'google';
$keyword = $_GET['keyword'] ?? '';

// 簡單快取(避免頻繁請求)
$cacheKey = "search_{$engine}_{$keyword}";
$cached = apcu_fetch($cacheKey);
if ($cached) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['html' => $cached, 'cached' => true]);
    exit;
}

// 獲取目標頁面
$urls = [
    'google' => "https://www.google.com/search?q=" . urlencode($keyword) . "&hl=zh-TW",
    'baidu'  => "https://www.baidu.com/s?wd=" . urlencode($keyword),
    // ...
];
$url = $urls[$engine] ?? $urls['google'];

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; SearchBot/1.0)',
    CURLOPT_SSL_VERIFYPEER => false, // 僅測試
]);
$html = curl_exec($ch);
curl_close($ch);

// 簡單提取結果區塊(實際需針對各引擎 DOM 解析)
// 這裡僅示範回傳原始 HTML
apcu_store($cacheKey, $html, 300); // 快取 5 分鐘

header('Content-Type: application/json; charset=utf-8');
echo json_encode(['html' => $html, 'cached' => false]);
?>

2. 搜尋建議/自動完成(Google Suggest API)

<?php
// api/suggest.php
$q = $_GET['q'] ?? '';
if (strlen($q) < 2) exit(json_encode([]));

$url = "https://suggestqueries.google.com/complete/search?client=firefox&q=" . urlencode($q);
$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 3]);
$response = curl_exec($ch);
curl_close($ch);

// Google 回傳: ['關鍵字', ['建議1', '建議2', ...]]
$data = json_decode($response, true);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data[1] ?? []);
?>

安全與合規注意事項

風險對策
開放式重導向嚴格白名單驗證 $engine,拒絕任意 URL
關鍵字注入urlencode() 編碼,禁止直接拼接
爬蟲封禁代理請求設定合理 User-Agent、限制頻率、使用代理 IP 池
隱私洩露不記錄用戶搜尋關鍵字與 IP 關聯日誌
版權/服務條款遵守各搜尋引擎 ToS,商業用途需申請官方 API (Custom Search API)

生產環境建議架構


用戶請求 → Nginx (靜態資源/快取/限流)
    → PHP-FPM (search.php: 白名單驗證 + 302 跳轉)
    
或 進階模式:
用戶請求 → Vue/React 前端 (AJAX)
    → API Gateway (限流/認證/快取)
    → PHP Worker (search_proxy.php: 代理抓取 + DOM 解析 + 結構化輸出)
    → Redis 快取 (TTL 5-30 分鐘)
    → 回傳 JSON 給前端渲染

總結

PHP 整合多搜尋引擎核心在於:**白名單驗證 + URL 編碼 + 302 重導向**。簡單場景直接跳轉最輕量;進階需求(聚合結果、去重、排序、快取)需引入**後端代理 + 非同步隊列 + 結構化解析**。切記遵守各引擎服務條款,商業用途請申請官方 API。

copyright © 萬盛學電腦網 all rights reserved