萬盛學電腦網

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

PHP cURL 模擬登錄 Discuz! 論壇並自動發帖實戰教程

PHP cURL 實戰:模擬登錄 Discuz! 論壇並發帖全流程

通過 cURL 模擬瀏覽器行為,實現論壇自動登錄、獲取 FormHash、發布帖子。本文詳細記錄完整流程、關鍵參數提取、Cookie 管理與反爬蟲應對技巧。

核心流程圖解


1. 訪問登錄頁 → 獲取 formhash (隱藏字段)
2. POST 登錄數據 + formhash → 獲取 Cookie 文件
3. 訪問發帖頁 → 獲取發帖 formhash (含 id 屬性)
4. POST 發帖數據 + formhash + Cookie → 發帖成功
5. 清理臨時 Cookie 文件

完整實現代碼

<?php
class DiscuzBot {
    private $baseUrl;
    private $cookieFile;
    private $ch;
    
    public function __construct(string $forumUrl) {
        $this->baseUrl = rtrim($forumUrl, '/');
        $this->cookieFile = sys_get_temp_dir() . '/dz_cookie_' . md5($forumUrl) . '.txt';
    }
    
    // 步驟 1: 獲取登錄頁 formhash
    private function getLoginFormhash(): string {
        $this->ch = curl_init($this->baseUrl . '/member.php?mod=logging&action=login');
        curl_setopt_array($this->ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_COOKIEJAR => $this->cookieFile,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ]);
        $html = curl_exec($this->ch);
        curl_close($this->ch);
        
        if (preg_match('/name="formhash"\s+value="([^"]+)"/i', $html, $m)) {
            return $m[1];
        }
        throw new RuntimeException('登錄頁 formhash 獲取失敗');
    }
    
    // 步驟 2: 提交登錄
    public function login(string $username, string $password, int $questionId = 0, string $answer = ''): bool {
        $formhash = $this->getLoginFormhash();
        
        $postData = [
            'formhash' => $formhash,
            'referer' => $this->baseUrl . '/',
            'loginfield' => 'username',
            'username' => $username,
            'password' => $password,
            'questionid' => $questionId,
            'answer' => $answer,
            'loginsubmit' => 'true',
        ];
        
        $this->ch = curl_init($this->baseUrl . '/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1');
        curl_setopt_array($this->ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($postData),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_COOKIEJAR => $this->cookieFile,
            CURLOPT_COOKIEFILE => $this->cookieFile,
            CURLOPT_REFERER => $this->baseUrl . '/member.php?mod=logging&action=login',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ]);
        
        $response = curl_exec($this->ch);
        curl_close($this->ch);
        
        // 判斷登錄成功:通常返回 sucmsg 或 重定向
        return strpos($response, 'succeed') !== false || strpos($response, 'welcome') !== false;
    }
    
    // 步驟 3: 獲取發帖頁 formhash
    private function getPostFormhash(int $fid): string {
        $this->ch = curl_init($this->baseUrl . "/forum.php?mod=post&action=newthread&fid=$fid");
        curl_setopt_array($this->ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_COOKIEFILE => $this->cookieFile,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $html = curl_exec($this->ch);
        curl_close($this->ch);
        
        // 發帖頁 formhash 有 id="formhash" 屬性
        if (preg_match('/id="formhash"\s+value="([^"]+)"/i', $html, $m)) {
            return $m[1];
        }
        throw new RuntimeException('發帖頁 formhash 獲取失敗');
    }
    
    // 步驟 4: 發帖
    public function postThread(int $fid, string $subject, string $message, array $tags = []): bool {
        $formhash = $this->getPostFormhash($fid);
        
        $postData = [
            'formhash' => $formhash,
            'subject' => $subject,
            'message' => $message,
            'topicsubmit' => 'yes',
            'tags' => implode(',', $tags),
            'extra' => '',
        ];
        
        $postUrl = $this->baseUrl . "/forum.php?mod=post&action=newthread&fid=$fid&extra=&topicsubmit=yes";
        
        $this->ch = curl_init($postUrl);
        curl_setopt_array($this->ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($postData),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_COOKIEFILE => $this->cookieFile,
            CURLOPT_REFERER => $postUrl, // 關鍵:Referer 必須為發帖頁
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ]);
        
        $response = curl_exec($this->ch);
        curl_close($this->ch);
        
        return strpos($response, 'succeed') !== false;
    }
    
    public function __destruct() {
        if (file_exists($this->cookieFile)) @unlink($this->cookieFile);
    }
}

// 使用示例
$bot = new DiscuzBot('https://bbs.example.com');
if ($bot->login('my_username', 'my_password')) {
    echo "登錄成功\n";
    if ($bot->postThread(2, '測試標題', '測試內容內容內容', ['測試', 'PHP'])) {
        echo "發帖成功\n";
    } else {
        echo "發帖失敗\n";
    }
} else {
    echo "登錄失敗\n";
}
?>

關鍵技術難點與解決方案

難點解決方案
FormHash 動態獲取兩次正則提取:登錄頁無 id、發帖頁有 id="formhash"
Cookie 持久化CURLOPT_COOKIEJAR (寫入) + CURLOPT_COOKIEFILE (讀取) 同一文件
Referer 驗證發帖請求必須設置 Referer 為發帖頁 URL
編碼問題論壇多為 GBK,發帖數據需 iconv 轉碼
驗證碼/安全提問需集成打碼平台或人工介入,質問答案需預知
反爬蟲策略隨機 User-Agent、請求間隔、IP 代理池、模擬人類行為

GBK 編碼轉換補丁

<?php
// Discuz 多為 GBK 編碼,發帖前轉換
$postData['subject'] = iconv('UTF-8', 'GBK//IGNORE', $subject);
$postData['message'] = iconv('UTF-8', 'GBK//IGNORE', $message);
$postData['tags'] = iconv('UTF-8', 'GBK//IGNORE', implode(',', $tags));
// 解析響應時轉回 UTF-8
$response = iconv('GBK', 'UTF-8//IGNORE', $response);
?>

法律與道德提醒

  • ⚠️ 僅供技術學習、授權測試、個人備份使用
  • ⚠️ 遵守《計算機信息網絡國際聯網管理暫行規定》及網站服務條款
  • ⚠️ 禁止用於垃圾信息發布、惡意灌水、帳號盜取等違法行為
  • ✅ 建議使用官方 API 或 RSS 訂閱獲取數據
copyright © 萬盛學電腦網 all rights reserved