在PHP中存储临时文件'


Storing temporary file's name and path in PHP

我试图创建一个基于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似乎是空的,导致无法检索其内容并删除它。

内容如下:

  1. 用户单击Run script
    • 1.1.创建tmp文件;
    • 1.2.脚本运行,输出重定向到tmp文件;
  2. 用户单击Check if script is running and delete the temporary file
    • 2.1.检查脚本是否仍在运行。如果脚本仍在运行,则除了回显之外什么也不做;
    • 2.2.如果脚本没有运行(已经完成),应该获取tmp文件的内容并删除该文件;

2.2遇到这个问题。如何永久存储临时文件的名称/完整路径?

这应该澄清了我所说的:在会话中存储$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);
    }
}