How to read the hash of a torrent file?

352 Views Asked by At

I'm trying to read the hash of a torrent file, so I'm using a simple program called torrenttools.

When I run this php file on my localhost:

<html>
    <head>
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
$torrenthash = shell_exec ("./torrenttools info '/var/www/html/torrents/Elle -JP- (Sharp X68000).torrent' | grep hash | cut -b 20-59 2>&1");
echo "<pre>".$torrenthash."</pre>";
?>
</head>
</html>

the shell_exec call returns nothing, however, if I run it from command line:

root@milton:/var/www/html# php test.php 
<html>
    <head>
<pre>03b0c32a389c280213506becabf6bd61ca71c38a
</pre></head>
</html

the file permisson seems to be ok as far as I know:

root@milton:/var/www/html# ls -l
total 34596
-rw-r--r-- 1 www-data www-data    10701 May  8 11:48 index.html.bak
-rw-r--r-- 1 www-data www-data     2404 May 10 14:06 index.php
-rw-r--r-- 1 www-data www-data       21 May  8 11:53 phpinfo.php
-rw-r--r-- 1 www-data www-data      324 May 18 07:40 test.php
drwxr-xr-x 2 www-data www-data     4096 May 18 07:26 torrents
-rwxrwxrwx 1 www-data www-data 35390656 May 12 02:33 torrenttools
-rw-r--r-- 1 www-data www-data     3012 May 18 07:25 upload.php

what am I doing wrong? this is driving me crazy

When I try running the test.php file from a browser I get a blank page, however, when I try run it from commandline it works perfectly. I am using the function shell_exec to call the program torrenttools to get the hash of a torrent.

Thanks in advance.

2

There are 2 best solutions below

0
hareth py On BEST ANSWER

Try the following perhaps?

  1. Use absolute file paths for the command tool, and the torrent file to ensure they can be located by the web server.
  2. Check the error logs for the Apache server and see if there is any error messages

You can try this code to print errors

$cmd = "./torrenttools info '/var/www/html/torrents/Elle -JP- (Sharp X68000).torrent' | grep hash | cut -b 20-59 2>&1";
$torrenthash = shell_exec($cmd);
echo "<pre>".$torrenthash."</pre>";

$errorOutput = shell_exec("echo $?");
echo "Error Output: ".$errorOutput;
2
Alex Howansky On

shell_exec should be used with caution. It's very easy to misuse it, which often leads to lots of headaches and security problems. Try to look for a specific solution for your problem.

The method to generate a hash from the torrent file is documented here.

You could use christeredvartsen/php-bittorrent to do this in pure PHP. From the shell, include the library in your project:

composer require christeredvartsen/php-bittorrent

Then just:

require_once 'vendor/autoload.php';
$torrent = \BitTorrent\Torrent::createFromPath('/path/to/file.torrent');
$hash = $torrent->getHash();