Parse, Edit And Create Torrent Files With PHP
A .torrent file contains assorted metadata that is stored in a “bencoded dictionary” format. Bencoding is a relatively simple cross-platform encoding used by BitTorrent and a dictionary is basically an associative array. You can find a high-level overview of the file structure here.
To open or edit a .torrent file in PHP you can either parse it manually or use one of the wrapper classes available on the web. I recommend the Torrent RW class (local mirror) because it has the best feature set compared to other wrappers that I tested. Below you will find a short overview of the class and a few example scripts that demonstrate how you can analyze .torrent files and create new torrents using this wrapper.
Pros
- Simple class interface for all important metadata.
- Parse and edit existing torrent files or build new torrent files from scratch.
- Request torrent statistics from tracker(s).
- Good inline documentation.
Cons
Note : these apply to the current version and bugs may be fixed in future releases.
- When encoding the torrent to a string, tries to
ksort()an object. This can trigger a warning message whenever outputting or saving a torrent file. Note that I’ve fixed this bug in the “local mirror” version, above. allow_url_fopenmust be enabled to get stats from trackers. This is generally considered bad practice security-wise.- The script requires PHP 5. This is not a major problem, just worth knowing if you want to incorporate TorrentRW in your own scripts and distribute them.
Examples
require_once 'Torrent.php'; /*********************** Get torrent info ***********************/ $torrent = new Torrent( './test.torrent' ); echo "<pre>\nPrivate: ", $torrent->is_private() ? 'yes' : 'no', "\nAnnounce: ", $torrent->announce(), "\nName: ", $torrent->name(), "\nComment: ", $torrent->comment(), "\nPiece_length: ", $torrent->piece_length(), "\nSize: ", $torrent->size( 2 ), "\nHash info: ", $torrent->hash_info(), "\nStats: "; var_dump( $torrent->scrape() ); echo "\nContents: "; var_dump( $torrent->content() ); //echo "\nSource data: ", $torrent; /*********************** Create a new torrent ***********************/ $torrent = new Torrent( array( 'test.mp3', 'test.jpg' ), 'http://torrent.tracker/announce' ); //Send it to the browser $torrent->send(); //Alternatively, you can also save it as a new file file_put_contents('new.torrent', (string) $torrent);
Thank you for shining a light on this. I’ve been using a very rudimentary torrent parser until now.