Friedpanseller
Friedpanseller

Reputation: 699

PHP doesn't echo until page loaded

I have in my index.php file

<?php
    ob_start();
    echo '<html>
              <head>
                  <style>
                      body {background-color: black; color: white}
                  </style>
              </head>
              <body>
                  <h2 id="greeting">Wait for page load</h2>
              </body>
          </html>';
    ob_flush();
    flush();
    sleep(100);
    echo '<script>document.getElementByID("greeting").innerHTML = "Page loaded!";</script>';
    ob_flush();
    flush();
?>

I thought it will send the HTML content to the client and they will see a "Wait for page load" text because it is flushed out, but on my website the webpage is just a blank white screen until the PHP code has finished executing (after 100 seconds) then everything on the page displays at once.

I have tried adding

echo str_repeat("<!--AAAAAAAAAAAA-->", 100);

after each echo as well to make sure it starts sending blocks of data to the browser but that didn't work either.

Is there a way for me to display the HTML content from the php file before the php code finishes executing?

Thanks!

EDIT: Everyone is telling me to use ob_start(); ob_flush(); and flush(); but I have used it in the code above already?

Upvotes: 0

Views: 2969

Answers (2)

hassan
hassan

Reputation: 8288

you need rather removing the ob_start from your script, or if ob_start is required within your program logic you may need to use ob_end_flush to

Flush (send) the output buffer and turn off output buffering

as follows:

<?php
ob_start();
echo '<html>
          <head>
              <style>
                  body {background-color: black; color: white}
              </style>
          </head>
          <body>
              <h2 id="greeting">Wait for page load</h2> '. time() .'
          </body>
      </html>';

ob_end_flush(); // <--------------

ob_flush();
flush();
sleep(2);
echo '<script>document.getElementById("greeting").innerHTML = "Page loaded!";</script>';
ob_flush();
flush();
?>

Upvotes: 4

salvatore
salvatore

Reputation: 521

The right way to do what you are trying to accomplish is using ajax. Using output buffering in this case is unreliable, because you may have other buffering layer other than yours.

I suggest you to read this good Q&A: PHP buffer ob_flush() vs. flush()

TL;DR Your web server might itself implement a buffering scheme (mod_deflate or content filter), which you have no influence over.

Upvotes: 0

Related Questions