McJohnson McJohnson - 3 months ago 9
PHP Question

Storing temporary file's name and path in PHP

I am trying to create a web-based interface that would allow a user to run a specific bash script in background, gets its content and delete the temporary file that has been used to store the output. So far I have this:

<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);
}
}


However, while everything seems to work according to plan, in the end,
$tmpfname
appears to be empty resulting in failure to retrieve its content and delete it.

It goes as follows:


  1. User clicks
    Run script
    .


    • 1.1.
      A tmp file is created;

    • 1.2.
      The script is ran and its output redirected to the tmp file;


  2. User clicks
    Check if script is running and delete the temporary file
    .


    • 2.1.
      A check is ran to see whether the script is still running. If the script is still running, nothing more is done but an echo;

    • 2.2.
      If the script is not running (has finished), it should get the content of the tmp file and delete the file;




The problem is encountered at
2.2
. How can I store the temporary file's name/full path permanently?

Answer

This should clarify what I meant when saying: store $tmpfname in a session. I do not garantee this code will work, there might be other errors.

// 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);
    }
}
Comments