Get torrent data with PHP

Tags: ,

To use this code you first need to include a file with the benc, bdec and hex2bin functions. You can get these functions from here: functions.phps.

<?php

include 'functions.php';

$torrent_data = bdec(file_get_contents('yourfile.torrent'));

To get the torrent data (like the announce url, the files etc) it is enough if we decode the content of the torrent.

On the other hand, if we want to read the number of seeds, leechs and downloads, we must encode the info part of the torrent, encrypt it with the sha1 function and convert the result to lowercase.

$info = strtolower(sha1(benc($torrent_data['info'])));
$scrape = str_replace('announce', 'scrape', $torrent_data['announce']);
$sources = bdec(@file_get_contents($scrape . '?info_hash=' . urlencode(hex2bin($info))));

Since it’s the scrape telling us how many seeds, leechs and downloads the torrent has, we have to change the announce url to the scrape url and read those informations.

Now we have everything we need to display the information. Let’s see how our torrent is structured.

echo '< pre>';
print_r($torrent_data);
echo '< /pre>';

We get an array with informations like the announce url, the creation date, another array with the files and more. What we want to display is the file (or files) in the torrent and the number of people sharing the files.

Let’s display the files in the torrent. The torrent structure is different if has one file or more files in it, so we first have to count the number of files and then, if the number is bigger than 1, do a loop and display every one of them, else display only the name of that one file.

$c = count($torrent_data['info']['files']);
echo '< h2>Files< /h2>';

if ($c > 1) {
	for ($i = 0; $i < $c; $i++) {
		echo $torrent_data['info']['files'][$i]['path']['0'] . '<br/>';
	}
} else {
	echo $torrent_data['info']['name'] . '<br/>';
}

Now we have our files listed. But to display the sources we find a little problem: the array in which the sources are stored is the binary version of our $info variable. We can reach them using the hex2bin function we have in our functions.php file.

$seeds = $sources['files'][hex2bin($info)]['complete'];
$leechs = $sources['files'][hex2bin($info)]['incomplete'];
$downloads = $sources['files'][hex2bin($info)]['downloaded'];

echo '< h2>Sources< /h2>' .
	'<b>Seeds:</b> ' . $seeds . '<br/>' .
	'<b>Leechs:</b> ' . $leechs . '<br/>' .
	'<b>Downloads:</b> ' . $downloads . '<br/>';

?>

I prepared a test file torrent.php. The torrent it is checking is a music torrent from thepiratebay.org.

You can download the source of this test file here: torrent.phps.

Same as always, if you don’t understand something you can ask it in the comments.

If you liked this post think about subscribing to my RSS feed and prevent missing anything interesting. It's free, fast and doesn't hurt. Promise. Click here.
Related posts: