我正在尝试创建一个基于Web的界面,允许用户在后台运行特定的bash脚本,获取其内容并删除用于存储输出的临时文件。到目前为止,我有这个:
<form method="POST">
<button type="submit" name="scan" class="btn btn-default">Run script</button>
</form>
<?php
if (isset($_POST['scan'])) {
$tmpfname = tempnam("/tmp", "SS-");
shell_exec('script.sh > '. $tmpfname .' &');
}
?>
<form method="POST">
<button type="submit" name="check-and-delete" class="btn btn-default">Check if script is running and delete the temporary file</button>
</form>
<?php
if (isset($_POST['check-and-delete'])) {
if (shell_exec("pgrep <its process>") != '') {
echo 'Script is running';
} else {
echo 'Script is NOT running';
echo '<pre>'. file_get_contents($tmpfname) .'</pre>';
unlink($tmpfname);
}
}
但是,虽然一切似乎都按计划运行,但最终$tmpfname
似乎为空,导致无法检索其内容并将其删除。
如下:
Run script
。
1.1.
创建了一个tmp文件; 1.2.
脚本已运行,其输出重定向到tmp文件; Check if script is running and delete the temporary file
。
2.1.
运行检查以查看脚本是否仍在运行。如果脚本仍在运行,那么除了回声之外别无其他; 2.2.
如果脚本没有运行(已经完成),它应该获取tmp文件的内容并删除文件; 2.2
遇到问题。如何永久存储临时文件的名称/完整路径 ?
答案 0 :(得分:1)
这应该说明我的意思:在会话中存储$tmpfname
。我不保证这段代码会起作用,可能还有其他错误。
// always start sessions
session_start();
<form method="POST">
<button type="submit" name="scan" class="btn btn-default">Run script</button>
</form>
<?php
if (isset($_POST['scan'])) {
$tmpfname = tempnam(sys_get_temp_dir(), "SS-");
shell_exec('script.sh > '. $tmpfname .' &');
// store in session
$_SESSION['tmpfname'] = $tmpfname;
}
?>
<form method="POST">
<button type="submit" name="check-and-delete" class="btn btn-default">Check if script is running and delete the temporary file</button>
</form>
<?php
if (isset($_POST['check-and-delete'])) {
if (shell_exec("pgrep <its process>") != '') {
echo 'Script is running';
} else {
echo 'Script is NOT running';
// retrieve from session
$tmpfname = $_SESSION['tmpfname'];
echo '<pre>'. file_get_contents($tmpfname) .'</pre>';
unlink($tmpfname);
}
}