PHP调用torrenttools获取Torrent哈希:浏览器运行无结果排查
问题排查与解决方案
1. 优先修正命令路径与环境变量差异
CLI以root运行时的工作目录、PATH环境变量,和web服务器用户(www-data)完全不同。你用./torrenttools相对路径调用程序,web用户执行时的当前目录未必是/var/www/html,会导致找不到程序。
修复操作:将torrenttools的路径改为绝对路径,修改PHP代码中的命令:
$torrenthash = shell_exec("/var/www/html/torrenttools info '/var/www/html/torrents/Elle -JP- (Sharp X68000).torrent' | grep hash | cut -b 20-59 2>&1");
2. 捕获完整的命令执行输出
当前命令仅截取部分结果,建议先单独执行torrenttools命令并输出所有内容,排查是否存在错误:
ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); // 输出命令的所有执行内容(包括错误信息) $command = "/var/www/html/torrenttools info '/var/www/html/torrents/Elle -JP- (Sharp X68000).torrent' 2>&1"; $output = shell_exec($command); echo "<pre>".htmlspecialchars($output)."</pre>";
访问页面后就能看到具体错误,比如权限不足、程序找不到等。
3. 验证文件与目录的实际权限
虽然你列出的文件权限看似正常,需确认torrent文件本身的权限:
ls -l /var/www/html/torrents/Elle\ -JP-\ \(Sharp\ X68000\).torrent
确保www-data用户对该文件有读权限(权限位至少为-rw-r--r--)。
另外检查系统是否启用SELinux或AppArmor,这类安全模块可能阻止web用户执行外部程序:
- 临时关闭SELinux测试:
若问题解决,需添加SELinux规则允许www-data执行torrenttools。sudo setenforce 0
4. 检查PHP配置限制
查看php.ini中是否禁用了shell_exec函数:
- 访问你的
phpinfo.php页面 - 搜索
disable_functions项,确认shell_exec不在禁用列表中
如果被禁用,需修改对应php.ini文件(通常在/etc/php/[版本]/apache2/php.ini或/etc/php/[版本]/fpm/php.ini),移除shell_exec后重启web服务器。
5. 安全转义特殊文件名
你的torrent文件名包含空格和括号,推荐用PHP的escapeshellarg()函数安全转义,避免shell解析错误:
$torrentFile = '/var/www/html/torrents/Elle -JP- (Sharp X68000).torrent'; $command = "/var/www/html/torrenttools info ".escapeshellarg($torrentFile)." | grep hash | cut -b 20-59 2>&1"; $torrenthash = shell_exec($command); echo "<pre>".htmlspecialchars($torrenthash)."</pre>";
内容的提问来源于stack exchange,提问作者Leandro
相关产品推荐
相关产品推荐

