下載的種子文件顯示為 xxx.php 而非 xxx.torrent,通常是因為:
download.php 輸出種子內容,但未正確設置 Content-Disposition 頭/download.php?id=123) 推斷文件名為 download.php下載後直接重命名:mv download.php movie.torrent,然後用迅雷、qBittorrent、uTorrent、Transmission 等 BT 客戶端打開。
修改下載腳本 download.php:
<?php
$torrentPath = '/path/to/real.torrent'; // 或從數據庫讀取二進制內容
$filename = 'movie.torrent'; // 用戶看到的文件名
if (!file_exists($torrentPath)) {
http_response_code(404);
exit('文件不存在');
}
// 關鍵頭部
header('Content-Type: application/x-bittorrent'); // 標準 MIME
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
header('Content-Length: ' . filesize($torrentPath));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: public');
// 輸出文件
readfile($torrentPath); // 比 file_get_contents + echo 更省記憶體
exit;
# Nginx
location /torrents/ {
alias /var/www/torrents/;
add_header Content-Type application/x-bittorrent;
add_header Content-Disposition 'attachment; filename="$1"';
# 或者讓 PHP 生成簽名 URL,Nginx X-Accel-Redirect 內部重定向
}
# Apache .htaccess
AddType application/x-bittorrent .torrent
Header set Content-Disposition "attachment"
<?php
// 簡單生成 .torrent (單文件模式)
function createTorrent(string $filePath, string $announceUrl, string $outputPath): bool
{
$fileName = basename($filePath);
$fileSize = filesize($filePath);
$pieceLength = 256 * 1024; // 256KB 每片
$pieces = '';
$fp = fopen($filePath, 'rb');
while (!feof($fp)) {
$piece = fread($fp, $pieceLength);
$pieces .= pack('H*', sha1($piece));
}
fclose($fp);
$dict = [
'announce' => $announceUrl,
'info' => [
'name' => $fileName,
'piece length' => $pieceLength,
'pieces' => $pieces,
'length' => $fileSize,
],
'creation date' => time(),
'created by' => 'PHP Torrent Creator 1.0',
];
$encoded = bencode($dict); // 需實現 Bencode 編碼
return file_put_contents($outputPath, $encoded) !== false;
}
// Bencode 簡易實現
function bencode($data): string
{
if (is_int($data)) return 'i' . $data . 'e';
if (is_string($data)) return strlen($data) . ':' . $data;
if (is_array($data)) {
$isList = array_keys($data) === range(0, count($data) - 1);
$res = $isList ? 'l' : 'd';
if ($isList) {
foreach ($data as $v) $res .= bencode($v);
} else {
ksort($data);
foreach ($data as $k => $v) {
$res .= bencode($k) . bencode($v);
}
}
return $res . 'e';
}
return '';
}
| 副檔名 | Content-Type | 用途 |
|---|---|---|
| .torrent | application/x-bittorrent | BitTorrent 種子 |
| .magnet | application/x-magnet | 磁力鏈接 (文本) |
| .php | application/x-httpd-php | PHP 腳本 (服務端解析) |
| .html | text/html | 網頁 |