Creating torrent files use PHPTracker

Published on Aug. 22, 2023, 12:12 p.m.

Before you start serving your files via Bittorrent, you need to create a metainformation file that contains all the data that the clients need to getit.

The file internally uses Bencode format in its entirety.PHPTracker comes with its own Bencode encoder/decoder library.

First of all, you’ll need to have a persistent storage (database) .This storage will be used while the client peers are announcing themselves.PHPTracker is shipped with MySQL persistence object so you don’t need to worry.

Here is a simple example how to make torrent files.

<?php
// -----------------------------------------------------------
// This is how to create a .torrent file from a physical file.
// -----------------------------------------------------------

// Registering autoloader, essential to use the library.
require( dirname(__FILE__).'/lib/PHPTracker/Autoloader.php' );
PHPTracker_Autoloader::register();

// Creating a simple config object. You can replace this with your object
// implementing PHPTracker_Config_Interface.
$config = new PHPTracker_Config_Simple( array(
    // Persistense object implementing PHPTracker_Persistence_Interface.
    // We use MySQL here. The object is initialized with its own config.
    'persistence' => new PHPTracker_Persistence_Mysql(
        new PHPTracker_Config_Simple( array(
            'db_host'       => '192.168.1.100',
            'db_user'       => 'misc',
            'db_password'   => 'misc',
            'db_name'       => 'misc',
        ) )
    ),
    // List of public announce URLs on your server.
    'announce'  => array(
        'http://php-tracker.dev/example_announce.php',
    ),
) );

// Core class managing creating the file.
$core = new PHPTracker_Core( $config );

// Setting appropiate HTTP header and sending back the .torrrent file.
// This is VERY inefficient to do! SAVE the .torrent file on your server and
// serve the saved copy!
header( 'Content-Type: application/x-bittorrent' );
header( 'Content-Disposition: attachment; filename="test.torrent"' );

// The first parameters is a path (can be absolute) of the file,
// the second is the piece size in bytes.
echo $core->createTorrent( 'netbeans.exe', 524288 );

To test that your torrent file is working correctly , you can use any torrent client , such as uTorrent or Torrents .

Creating announce URL

Once your clients downloaded the .torrent file representing your original file (see Creating torrent files) you will have to provide them with a list of other peers online.

This interface is the announce URL (or multiple announce URLs) that you encoded in your .torrent file.Clients will make regular GET requests to this URL while they are online telling your server the status of their download.

You will have to use the same database profile that you used .torrent file .

Here is example code:

<?php
// ---------------------------------------
// This is how to set up an announce URL.
// ---------------------------------------

// Registering autoloader, essential to use the library.
require( dirname(__FILE__).'/lib/PHPTracker/Autoloader.php' );
PHPTracker_Autoloader::register();

// Creating a simple config object. You can replace this with your object
// implementing PHPTracker_Config_Interface.
$config = new PHPTracker_Config_Simple( array(
    // Persistense object implementing PHPTracker_Persistence_Interface.
    // We use MySQL here. The object is initialized with its own config.
    'persistence' => new PHPTracker_Persistence_Mysql(
        new PHPTracker_Config_Simple( array(
            'db_host'       => '192.168.1.100',
            'db_user'       => 'misc',
            'db_password'   => 'misc',
            'db_name'       => 'misc',
        ) )
    ),
    // The IP address of the connecting client.
    'ip'        => $_SERVER['REMOTE_ADDR'],
    // Interval of the next announcement in seconds - sent back to the client.
    'interval'  => 60,
) );

// Core class managing the announcements.
$core = new PHPTracker_Core( $config );

// We take the parameters the client is sending and initialize a config
// object with them. Again, you can implement your own Config class to do this.
$get = new PHPTracker_Config_Simple( $_GET );

// We simply send back the results of the announce method to the client.
echo $core->announce( $get );

Running seed server running .

To start seeding server daemon.PHPTracker provides you with a pure PHP seeding server.

When you start running your seeder server process, it will create branches itself.The first child process will listen to incoming connections and take care of serving files, and the second child process will constantly emulate announcements to your database for your client peers.

Remember, that you have to use PHP command line interface.

$ php example_seeder.php

Here is a simple example how to run seeds .

<?php
// --------------------------------------
// This is how to start a seeding server.
// --------------------------------------

// [!] Run this file in CLI only!
// /usr/bin/php example_seeder.php

// Registering autoloader, essential to use the library.
require( dirname(__FILE__).'/lib/PHPTracker/Autoloader.php' );
PHPTracker_Autoloader::register();

// Persistense object implementing PHPTracker_Persistence_Interface.
// We use MySQL here. The object is initialized with its own config.
$persistence = new PHPTracker_Persistence_Mysql(
    new PHPTracker_Config_Simple( array(
        'db_host'       => 'localhost',
        'db_user'       => 'misc',
        'db_password'   => 'misc',
        'db_name'       => 'misc',
    ) )
);

// Setting up seeder peer. This will listen to connections and serve files.
$peer = new PHPTracker_Seeder_Peer(
    new PHPTracker_Config_Simple( array(
        'persistence'               => $persistence,
        // PUBLIC address of the seeder server. This will be used for announcements (ie. sent to the clients).
        'seeder_address'            => '192.168.2.123',
        // Don't forget the firewall!
        'seeder_port'               => 6881,
        // Optional parameter for IP to open socket on if differs from external.
        //'seeder_internal_address' => '192.168.2.123',
        // Number telling how many processes should be forked to listen to incoming connections.
        'peer_forks'                => 10,
        // If specified, gives a number of outsider seeders to make self-seeding stop.
        // This saves you bandwidth - once your file is seeded by others, you can stop serving it.
        // Number of seeders is permanently checked, but probably 1 is too few if you want your file to be available always.
        'seeders_stop_seeding'      => 5,
        // Intializing file logger with default file path (/var/log/phptracker.log).
        // File logger might accept config object with keys file_path_messages
        // and file_path_errors as absolute path of log files for messages and
        // errors respectively.
        'logger'  => new PHPTracker_Logger_File(),
    )
) );

// We set up a seeding server which starts the seeding peer, and makes regular
// announcements to the database adding itself to the peer list for all
// active torrents.
$server = new PHPTracker_Seeder_Server(
     new PHPTracker_Config_Simple( array(
        'persistence'           => $persistence,
        'peer'                  => $peer,
         // Intializing file logger with default file path (/var/log/phptracker.log).
        'logger'                => new PHPTracker_Logger_File(),
    )
) );

// Starting "detached" means that process will unrelate from terminal and run as deamon.
// To run in terminal, you can use start().
// Detached running requires php-posix.
$server->startDetached();