Output part of the HTML file before running time-consuming commands

28 Views Asked by At

I'm trying to use output buffers in PHP to update the interface of the web page.

The simplified HTML structure is as follow:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>Some Header Here</h1>
<?php
ob_implicit_flush(true);
$buffer = str_repeat(" ", 4096)."\r\n<span></span>\r\n"; // to ensure the browser to print ("flush") the output
ob_start();

echo '<p>Start operation</p>' . $buffer . PHP_EOL;
ob_flush(); flush(); ob_clean();

$response = shell_exec('a_long_running_command1'); // which will execute for around 3 minutes
echo '<p>Command 1 Response: ' . $response . '</p>' . PHP_EOL;
ob_flush(); flush(); ob_clean();

$response = shell_exec('a_long_running_command2'); // which will execute for around 5 minutes
echo '<p>Command 2 Response: ' . $response . '</p>' . PHP_EOL;
ob_flush(); flush(); ob_clean();

ob_end_flush();
echo '<p>Task Complete</p>' . PHP_EOL;
?>
</body>
</html>

whereas Command 1 & 2 are CPU-intensive tasks running on a Linux-based server.

However, once entered the page, the page is blank (and the browser (Chrome) indicates it keeps loading) until Command 1 is complete. How can I display the first <h1> header and the "Start Operation" heading first?

One more greedy question: is it possible for me to display the elapsed time on the page so that the user knows the command is still running?


I know I can achieve this via AJAX calls, but I don't want the user to:

  1. refresh the page (which might lead to Command 1 & 2 being run for more than 1 instance in the server)
  2. know the AJAX call so that he can replay the AJAX call
0

There are 0 best solutions below