从 php 文件执行脚本

executing a script from a php file

我有一个被网站调用的 php 文件:

示例:serial_tx.php?v=W100

在 php 中,我写了一个日志文件,我可以在其中查看我收到了哪个字符串 v(在本例中为 W100)。

网络服务器托管在 Raspberry Pi 上,应该将此数据发送到 uart。

文件位置:

/SCRIPTS/serial_tx.php
/SCRIPTS/c/jmsend/serial_tx  // the executable, compiled from a C script

如果我在网络服务器的根目录下,并且从我的 Pi 控制台,我 运行

sudo /var/www/html/SCRIPTS/c/jmsend/serial_tx W100

我收到正确发送的命令。

我用系统尝试 php 文件,shell_exec 并执行但没有成功。

shell_exec("sudo /var/www/html/SCRIPTS/c/jmsend/serial_tx ".$ric);

$ric是接收到的命令。 我也尝试过不同的路径设置(从 Pi root 或 webserver root 开始)。 所有文件都有 777 作为权限。

/etc/sudoers 中的类似内容应该可以让您的 Web 服务器用户 运行 毫无问题地执行该特定命令:

Cmnd_Alias SERIAL = /var/www/html/SCRIPTS/c/jmsend/serial_tx *
www-data ALL=(ALL) NOPASSWD: SERIAL

请注意,您必须 escape user input才能使用它:

$ric = escapeshellarg($_GET["v"]);
shell_exec("sudo /var/www/html/SCRIPTS/c/jmsend/serial_tx $ric");

您还应该了解 exec()shell_exec() 之间的区别,特别是您不能使用 shell_exec().

检查失败
$ric = escapeshellarg($_GET["v"]);
exec("sudo /var/www/html/SCRIPTS/c/jmsend/serial_tx $ric", $output, $return);
if ($return !== 0) {
    // let the user know something didn't work
}

当然,这假定您的可执行文件已写入 return 适当的错误代码。