本文提供完整的 PHP cURL 實作,模擬登入 QQ 空間並抓取訪客資訊,涵蓋 Cookie 管理、加密算法、請求簽名、反爬蟲應對等核心技術。注意:僅供技術學習研究,實際使用請遵守平台服務條款與法律法規。
<?php
// 目錄結構
// qq_visitor/
// ├── config.php # 設定檔
// ├── QQVisitorCapture.php # 核心採集類
// ├── QQEncryption.php # QQ 加密算法
// ├── CookieManager.php # Cookie 持久化管理
// └── run.php # 入口腳本
<?php
// config.php
return [
'app_dir' => __DIR__,
'cookie_file' => __DIR__ . '/cookies/app.cookie.txt',
'capture_interval' => 3, // 秒,避免頻率限制
'request_timeout' => 20,
'debug' => true,
'end_line' => "\n",
// 多帳號輪換(降低封號風險)
'accounts' => [
['uin' => '2064556526', 'password' => 'your_password'],
['uin' => '483258700', 'password' => 'your_password'],
// ...
],
// 上傳服務配置(可選)
'upload' => [
'security_key' => 'your_key',
'service_id' => 'your_id',
'service_address' => 'https://api.yourservice.com/upload',
],
];
<?php
// QQEncryption.php
class QQEncryption {
// 計算 g_tk (關鍵簽名參數)
public static function getGTK(string $skey): int {
$hash = 5381;
for ($i = 0, $len = strlen($skey); $i < $len; ++$i) {
$hash += ($hash << 5) + ord($skey[$i]);
}
return $hash & 2147483647; // 32 位有符號整數
}
// 密碼加密:MD5(MD5(pass) + uin) + vcode
public static function getEncryption(string $password, string $uin, string $vcode): string {
$md5Pass = strtoupper(md5($password));
$str1 = pack('H*', $md5Pass); // hex 轉二進制
$str2 = strtoupper(md5($str1 . $uin));
return strtoupper(md5($str2 . strtoupper($vcode)));
}
// URL 解碼修正
public static function decodeURIComponent(string $str): string {
return urldecode(preg_replace('/%u([0-9a-f]{4})/i', '$1;', $str));
}
// JavaScript 時間戳模擬
public static function loginJsTime(): string {
list($mic, $time) = explode(' ', microtime());
return $time . sprintf('%03d', $mic * 1000);
}
}
<?php
// CookieManager.php
class CookieManager {
private string $file;
private array $cookies = [];
public function __construct(string $file) {
$this->file = $file;
$this->load();
}
public function load(): void {
if (file_exists($this->file)) {
$content = file_get_contents($this->file);
$this->cookies = json_decode($content, true) ?? [];
}
}
public function save(): void {
$dir = dirname($this->file);
if (!is_dir($dir)) mkdir($dir, 0755, true);
file_put_contents($this->file, json_encode($this->cookies), LOCK_EX);
}
public function get(string $domain): array {
return $this->cookies[$domain] ?? [];
}
public function set(string $domain, array $cookies): void {
$this->cookies[$domain] = $cookies;
$this->save();
}
public function clear(string $domain): void {
unset($this->cookies[$domain]);
$this->save();
}
// 格式化為 cURL CURLOPT_COOKIE 字串
public function formatForCurl(string $domain): string {
$cookies = $this->get($domain);
return implode('; ', array_map(fn($k, $v) => "$k=$v", array_keys($cookies), $cookies));
}
}
<?php
// QQVisitorCapture.php
require_once 'QQEncryption.php';
require_once 'CookieManager.php';
class QQVisitorCapture {
private string $uin;
private string $password;
private CookieManager $cookieManager;
private int $timeout;
private bool $debug;
private string $endLine;
private array $headers = [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Referer: https://qzone.qq.com/',
'Origin: https://qzone.qq.com',
];
public function __construct(string $uin, string $password, string $cookieFile, int $timeout, bool $debug, string $endLine) {
$this->uin = $uin;
$this->password = $password;
$this->cookieManager = new CookieManager($cookieFile);
$this->timeout = $timeout;
$this->debug = $debug;
$this->endLine = $endLine;
}
public function getVisitorInfo(): ?array {
// 1. 確保登入
if (!$this->ensureLogin()) {
return null;
}
// 2. 獲取 g_tk
$cookies = $this->cookieManager->get('qzone.qq.com');
$skey = $cookies['skey'] ?? $cookies['p_skey'] ?? '';
if (!$skey) {
$this->log('缺少 skey/p_skey,需重新登入');
return null;
}
$gtk = QQEncryption::getGTK($skey);
// 3. 請求訪客介面
$url = "https://h5.qzone.qq.com/proxy/domain/r.qzone.qq.com/cgi-bin/user/cgi_personal_card.php?uin={$this->uin}&g_tk={$gtk}";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_HTTPHEADER => $this->headers,
CURLOPT_COOKIE => $this->cookieManager->formatForCurl('qzone.qq.com'),
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_FOLLOWLOCATION => true,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
$this->log("請求失敗: HTTP $httpCode");
return null;
}
// 4. 解析回應(JSONP 格式)
if (preg_match('/_Callback\((.*)\)/', $response, $matches)) {
$data = json_decode($matches[1], true);
return $this->parseVisitorData($data);
}
$this->log('回應格式異常: ' . substr($response, 0, 200));
return null;
}
private function ensureLogin(): bool {
$cookies = $this->cookieManager->get('qzone.qq.com');
if (isset($cookies['uin'], $cookies['skey'])) {
$this->log('使用現有 Cookie');
return true;
}
return $this->login();
}
private function login(): bool {
$this->log('開始登入...');
// 1. 獲取驗證碼
$vcUrl = 'https://ssl.ptlogin2.qq.com/ptqrshow?appid=549000912&e=2&l=M&s=3&d=72&v=4&t=0.123&daid=5&pt_3rd_aid=0';
$vcResponse = $this->curlGet($vcUrl);
// 解析驗證碼圖片、提取 qrsig...
// 實際需處理滑塊驗證碼、二維碼掃描等複雜流程
// 此處簡化:假設已有驗證碼
// 2. 提交登入(簡化流程)
$loginUrl = 'https://ssl.ptlogin2.qq.com/ptlogin2';
$postData = [
'u' => $this->uin,
'p' => QQEncryption::getEncryption($this->password, $this->uin, $vcode),
'verifycode' => $vcode,
'pt_vcode_v1' => 0,
'ptredirect' => 1,
'h' => 1,
't' => 1,
'g' => 1,
'from_ui' => 1,
'ptlang' => 2052,
'action' => '0-0-' . time(),
'js_ver' => '20032614',
'js_type' => 1,
'login_sig' => $loginSig,
'pt_uistyle' => 40,
'aid' => 549000912,
'daid' => 5,
];
$response = $this->curlPost($loginUrl, http_build_query($postData));
// 解析登入結果、提取 Cookie、驗證成功...
// 3. 儲存 Cookie
$this->extractAndSaveCookies($response);
return true; // 簡化
}
private function curlGet(string $url): string {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_HTTPHEADER => $this->headers,
CURLOPT_COOKIE => $this->cookieManager->formatForCurl('qzone.qq.com'),
CURLOPT_SSL_VERIFYPEER => true,
]);
$resp = curl_exec($ch);
curl_close($ch);
return $resp;
}
private function curlPost(string $url, string $postData): string {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array_merge($this->headers, ['Content-Type: application/x-www-form-urlencoded']),
CURLOPT_COOKIE => $this->cookieManager->formatForCurl('qzone.qq.com'),
CURLOPT_SSL_VERIFYPEER => true,
]);
$resp = curl_exec($ch);
curl_close($ch);
return $resp;
}
private function extractAndSaveCookies(string $response): void {
// 從 Set-Cookie 標頭或回應中提取
// 實際需解析 HTTP 標頭,此處簡化
}
private function parseVisitorData(array $data): array {
// 解析 QQ 空間回應結構
return $data['data']['visitor'] ?? [];
}
private function log(string $msg): void {
if ($this->debug) {
echo date('H:i:s') . " $msg" . $this->endLine;
}
}
}
<?php
// run.php
require_once 'config.php';
require_once 'QQVisitorCapture.php';
$config = require 'config.php';
$account = $config['accounts'][array_rand($config['accounts'])]; // 隨機選帳號
$capture = new QQVisitorCapture(
$account['uin'],
$account['password'],
$config['cookie_file'],
$config['request_timeout'],
$config['debug'],
$config['end_line']
);
$visitors = $capture->getVisitorInfo();
if ($visitors) {
echo "成功獲取 " . count($visitors) . " 位訪客\n";
// 上傳至自己的服務
if (!empty($config['upload'])) {
uploadToService($visitors, $config['upload']);
}
} else {
echo "獲取失敗,清除 Cookie 重試\n";
$capture->clearCookies();
}
function uploadToService(array $visitors, array $config): void {
$ch = curl_init($config['service_address']);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(['visitors' => $visitors, 'key' => $config['security_key']]),
CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'X-Service-ID: ' . $config['service_id']],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $config['request_timeout'],
]);
curl_exec($ch);
curl_close($ch);
}
| 防禦機制 | 應對策略 |
|---|---|
| IP 限流 | 代理 IP 池、住宅代理、請求間隔隨機化 (3-10秒) |
| 驗證碼(滑塊/點選/文字) | 第三方打碼平台、深度學習識別、人工介入 |
| 瀏覽器指紋 | Puppeteer/Playwright 無頭瀏覽器、偽裝 User-Agent/Canvas/WebGL |
| 行為分析 | 模擬真人操作軌跡、隨機停留、滾動、點擊 |
| 加密參數簽名 | 逆向分析 JS 加密邏輯(如上方 g_tk、密碼加密) |
| 帳號風控 | 多帳號輪換、降低頻率、養號(正常瀏覽行為) |