0

I need to run an index.php script that calls an external script which takes a few seconds to run, before redirecting to index.html. Is it possible for the php script to load the same index.html into the browser in the meantime so the screen isn't blank? If not what would be the way to handle this? My best effort is:

<?php
    $doc = new DOMDocument();
    $doc->loadHTMLFile("index.html");
    echo $doc->saveHTML();
    shell_exec('./shellscript.sh');
    header('Location: index.html');
    exit;
?>

which fails to load with:

Warning: DOMDocument::loadHTMLFile(): Tag nav invalid in index.html, line: 33 in {pathto}/index.php on line 3

That line of index.html is - <nav class="navbar navbar-inverse navbar-fixed-top">

Grateful for assistance.

2
  • This way it cannot work, because headers are sent before content. You cannot send any content before finishing sending headers. Commented Aug 20, 2015 at 15:56
  • shell_exec() blocks, so header() wouldn't run until the shell script exits. you COULD try to run it in the background, e.g. shell_exec('foo &'), but then you couldn't wait for the results. Commented Aug 20, 2015 at 15:57

1 Answer 1

1

This is certainly possible. You can close the connection and run the command afterwards. This avoids the problem of shell_exec blocking processing.

It's a little bit tricky to get it to work but it's something like:

 ignore_user_abort(true); // prevent the PHP script from being killed when the connection closes
 header("Location: /index.html");
 header("Connection: Close");
 flush();
 // the connection should now be closed, the user is redirected to index.html
 shell_exec('./shellscript.sh');

If you're also sending content you might need to send a Content-Length header. If you're using sessions be sure to close the session with session_close(). You should also flush any output buffers.


The DOMDocument error you're getting is unrelated.

Sign up to request clarification or add additional context in comments.

2 Comments

Looks promising but my browser is still held back while the script runs.
Try sending the Content-Length header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.