用PHP从HTML页面执行shell脚本



我正在尝试使用PHP从HTML页面执行shell脚本。我在这里找到了一个以前的例子,我一直试图遵循,但我有一个问题。我不确定原因是什么,但没有返回错误,也没有从bash脚本创建文件。

index . php:

<!DOCTYPE html>
<html>
<head>
<style></style>
</head>
<body>
<form action="./test.php">
<input type="submit" value="Open Script">
</form>
</body>
</html>

test.php

<?php
exec("./bash_script.sh");
header('Location: http://local.server.edu/ABC/abc_test/');
?>

bash_script.sh

#!/bin/bash
touch ./test_file.txt

我注意到的一件事可能是导致问题的原因,似乎本地服务器上的路径与文件系统不完全匹配。

如果我将脚本中的所有相对路径切换为绝对路径,例如:/local/sequence/temp/abc_test/file.exe

然后点击按钮运行脚本后,我得到一个错误说:The requested URL /local/sequence/temp/abc_test/test.php was not found on this server

编辑:这三个文件位于/local/sequence/temp/abc_test有一个符号链接指向/export/www/htdocs/ABC

错误信息似乎表明没有找到test.php。如前所述,它需要位于与index.php

相同的目录中。您已经测试了实际的bash脚本,因此我们可以继续假设它在接收提交的脚本的执行中。

我建议把所有的web内容放到一个页面中,因为你可以测试发送和接收输入。

<?php
// for testing
// exec("./bash_script.sh");
// check for POST submission (this is not just reading data)
if(isset($_POST['runScript'])) {
// die('Request received');
exec("./bash_script.sh");
// It’s always proper to redirect after post :)
header('Location: http://local.server.edu/ABC/abc_test/');
die;
}
// finished with logic; show form
?>
<!DOCTYPE html>
<html>
<head>
<style></style>
</head>
<body>
<form method="POST">
<input type="submit" name="runScript" value="Open Script">
</form>
</body>
</html>

请注意,我为提交按钮添加了name属性,并使表单在提交到调用页面时使用POST方法(没有操作意味着提交给自己)。

我还留下了一些注释动作,以便在必要时帮助调试

您可能需要调整bash脚本的路径。目前,它将在与index.php相同的目录中查找,这不是您在生产环境中想要做的事情。

您将能够以某种方式做到这一点,但允许从php页面执行此类操作总是非常危险的。