Torrent File

Packagist GitLab GitHub Bitbucket Gitea

A PHP Class to work with torrent files


composer require sandfoxme/torrent-file


Load existing torrent file


use SandFox\Torrent\TorrentFile;

// from file
$torrent = TorrentFile::load('debian.torrent');
// from string
$torrent = TorrentFile::loadFromString(file_get_contents('debian.torrent'));
// from stream
$torrent = TorrentFile::loadFromStream(fopen('debian.torrent', 'r'));

Create torrent file for existing directory or file


use SandFox\Torrent\TorrentFile;

$torrent = TorrentFile::fromPath('/home/user/ISO/Debian', [
    'pieceLength' => 512 * 1024,    // torrent chunk size (default: 512 KiB)
    'md5sum' => false,              // generate md5 sums for files (default: false)
    'sortFiles' => true,            // sort files in info dictionary by name (default: true)

// pass an instance of PSR-14 event dispatcher to receive progress events:
$torrent = TorrentFile::fromPath('/home/user/ISO/Debian', [], $eventDispatcher);
// dispatcher will receive instances of \SandFox\Torrent\FileSystem\FileDataProgressEvent
//    only in 2.0 and later

Save torrent file


// to file

// to string. for example, for downloading
header('Content-Type: application/x-bittorrent');
header('Content-Disposition: attachment; filename="' . urlencode($torrent->getFileName()) . '"');
echo $torrent->storeToString();

// to stream. useful for psr-7
    ->withHeader('Content-Type', 'application/x-bittorrent')

Basic fields manipulation


// main announce url
$announce = $torrent->getAnnounce();

// additional announce urls
$announces = $torrent->getAnnounceList();
// plain ordered list
// or with tier grouping
    ['', ''],

// creation date
$created = $torrent->getCreationDate();

// comment
$comment = $torrent->getComment();
$torrent->setComment('This is a very cool torrent');

// created by
$createdBy = $torrent->getCreatedBy();

// private marker
$private = $torrent->isPrivate();

Possible future features

  • Files model (chunks and offsets for files)
  • Chunks model (files and their offsets, chunk data validation)
  • Info verification for existing files on disk

Upgrade from 1.x

Breaking changes:

  • PHP 7.4 is now required.
  • Custom event system based on FileDataProgress is removed. It was never documented anyway.


The library is available as open source under the terms of the MIT License.