在 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. 检查是运行看脚本是否还在运行ning。如果脚本仍然是 运行ning,除了 echo 什么都不做;
    • 2.2.如果脚本不是运行ning(已经完成),应该获取tmp文件的内容并删除文件;

2.2 遇到问题。如何永久name/full存储临时文件的name/full路径?

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