0

I have a php script that gets called from a upload form, the script puts entries into a database. I would like to see the results on my browser as the script is running. I am using the code below, but the output shows up after the whole script has finished executing. My server is Apache2 running on Ubuntu. I thought by using ob_start(); I can see the progress while the script is executing. Am I doing something wrong in my code?

 ob_start();
 foreach ($csvAsArray as $value)
 {
  $username = $value[0];
  $password = $value[1];
  $db->insert($username, $password, $machine);
  echo $username . " Inserted into database! <br />";
  ob_flush();
 }
 echo('done.');
 ob_end_flush();
3

2 Answers 2

1

You don't need ob_start :

<?php

 for($i=0;$i<100;$i++)
 {
  echo $i;
  flush();
  ob_flush();
  sleep(1);
 }
 echo 'done.';
 ob_end_flush();

 ?>

From Comment:

php flush : Flushes the system write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats. flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

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

3 Comments

Please provide explanation to the code, for other users that will need help with similar issues in future
php flush : Flushes the system write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats. flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.
@christophe It'd be more helpful if you'd explain your code inside your answer
0

Try with this use ob_get_contents() to get data

   ob_start();
   foreach ($csvAsArray as $value)
   {
     $username = $value[0];
     $password = $value[1];
     $db->insert($username, $password, $machine);
     echo $username . " Inserted into database! <br />";

 }
  $data = ob_get_contents();
  ob_end_clean();
  var_dump($data);

Comments

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.