menu

Friday, November 8, 2013

Real-time updating of php output using flush() in all browsers

Heyy guys,

These days, i'm kinda into hot stuff each day but kinda not having time to document all those. So here i got a little time, let's skip the bla bla.

What exactly is real-time updating means?

Have you ever seen how php output is shown on the browser? No matter what length code or how many loops you put into, the browser always wait to get EVERYTHING, every tiny thing from php output before showing it to the user. Now this isnt convinient eh?

Let's take a scenario where you have to get 1000 records from a database and do very high time consuming calculations on each record. So under normal conditions the user will be looking at a blank page for several minutes [or hours depending on your processor :D ]. This isnt any fault of php, of course if you run php from the terminal (WAMP users dont look confused now) you'll see the output in realtime. So what's preventing it?

 BUFFERING

The Quickie Solve

Just like every other problem there's the easy short code to do this.
Tested with Chrome and Firefox in a standard LAMP server without any server config changes

Usual php output code

  1. echo "add this";
  2. sleep(5);
  3. echo "Program Output";


output [the whole thing displays after 5 seconds]

  1. add thisProgram output


php with buffering off

  1. echo "add this";
  2. echo str_pad("",1024," "); //BROWSER TWEAKS
  3. echo " <br />" //BROWSER TWEAKS
  4. //telling php to show the stuff as soon as echo is done
  5. ob_flush();
  6. flush();
  7. //just a usual sleep
  8. sleep(5);        
  9. //second echo statement
  10. echo "Program Output";
  11. ob_flush();
  12. flush();



output [the whole thing displays after 5 seconds]

  1. add this
    [waiting 5 seconds]
    Program output



So let's talk about buffering. The feature-thingy that put the whole output at last is because there are several layers of buffering undergoing on the php output to make the output process efficient
1) by php       : the ob_* functions are related to this, ob_flush() would stop/flush the buffer
2) by server    : gzip compression, output_buffering in php5.ini does these
3) by client     : browsers like to do less work, so they wait for considerable about of data to come before showing them to the user

Important tweaks of the code

1) echo str_pad("",1024," "); //BROWSER TWEAKS
As i mentioned browsers do their own buffering to wait for some amount of data before showing content to user
FF        - 512 bytes
chrome - 1024 bytes
IE         - why would you ask? :D
What above code does is adding 1024 blanks to the output, just to make it complete

2) echo " <br />" //BROWSER TWEAKS

Even after above tweak i found that Chrome doesn't show the output as expected. After few more hours of trial and error [at the workplace] I found that it need to read a newline before actually giving any output. Strange huh? So i simply added a html newline and VIOLA :D

Now the code seems working but only buffering (1) and (3) seem to be addressed. So lets make the code complete in a case the server had some bad-ass buffering and caching going. But you wont need all of these, just do trial and error to find the best methods for you.

  1. // Turn off output buffering
  2. ini_set('output_buffering', 'off');
  3. // Turn off PHP output compression
  4. ini_set('zlib.output_compression', false);
  5.          
  6. //Flush (send) the output buffer and turn off output buffering
  7. while (@ob_end_flush());
  8.          
  9. // Implicitly flush the buffer(s)
  10. ini_set('implicit_flush', true);
  11. ob_implicit_flush(true);
  12. echo "add this";
  13. echo str_pad("",1024," ");
  14. echo "<br />";
  15. ob_flush();
  16. flush();
  17. sleep(5);        
  18. echo "Program Output";
  19. ob_flush();
  20. flush();

References

69 comments:

  1. Its really helpful for me to understand. Thanks.
    If anyone wants to Learn Web Designing in Chennai go to the Besant Technologies which is No.1 Training Institute in Chennai.

    ReplyDelete
  2. Thanks. I'm trying to display the output from a unix command line program. how would this work with a system() call that outputs every few seconds?

    ReplyDelete
    Replies
    1. does the php script call the system() command?

      Delete
  3. Much appreciated. I'm attempting to show the yield from an unix charge line program.
    Best Web Design

    ReplyDelete
  4. Doesn't work for me in FF or Chrome, strange

    ReplyDelete
    Replies
    1. tested on FF/chrome/IE at the time of writing the script, try increasing the str_pad value from 1024 -> 2048 and on, might resolve :)

      Delete
  5. It works perfectly in FF.

    I deleted " ob_flush();" because I received warnings about it.

    Thanks

    ReplyDelete
  6. After days of trial and error I finally came across this page. Worked perfectly for me. Thank you.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete

  8. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.


    Peridot Systems Chennai

    ReplyDelete

  9. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up.

    SEO training in Adyar

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Thanks for posting useful information.You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article...very interesting to read..please sharing like this information......
    oneplus mobile service center in chennai
    oneplus mobile service center
    oneplus mobile service centre in chennai
    oneplus mobile service centre
    oneplus service center near me
    oneplus service
    oneplus service centres in chennai
    oneplus service center velachery
    oneplus service center in vadapalani

    ReplyDelete
  12. Thanks for provide great information and looking beautiful blog. If you wish to learn get connected with Advanced Cyber Security Course. I hope below information will help you.
    Ethical Hacking Training in chennai
    Best Training Institute in Chennai

    ReplyDelete
  13. Whatsapp Group Link - 5000+ Updated Whatsapp Groups
    whatsapp group link Click The link And Join Whatsapp New Groups, Dating, Business promositions Groups

    ReplyDelete
  14. I must appreciate you for providing such a valuable content for us. This is one amazing piece of article. Helped a lot in increasing my knowledge.SAS Training in Bangalore

    ReplyDelete
  15. I Love your article. You can visit my website : m.bee.mp3.com

    ReplyDelete
  16. Thank you so much for such an wonderful blog. I’m really thankful to you for this informative Blog .

    Computer Repairing Course in Delhi

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. Snapdeal Winner List here came up with an Offer where you can win Snapdeal prize list 2020 by just playing a game & win prizes.
    Snapdeal winner name2020 also check the Snapdeal lucky draw2020

    ReplyDelete
  20. You can download free games and apps on your android mobile tweakbox apk

    ReplyDelete
  21. It’s difficult to find experienced people in this particular topic, however, you seem like you know what you’re talking about! Thanks
    Tech news

    ReplyDelete
  22. if you are searching for the result of Matka, Satta Matka, Boss Matka, Kalyan Matka Tips, Satta Matka, Matka, Sattamatka, Matka Satta, Matka Charts, Matka Satta Result, Fix Matka

    ReplyDelete
  23. I must appreciate you for providing such a valuable content for us. This is one amazing piece of article. Helped a lot in increasing my knowledge.
    AWS training in chennai | AWS training in annanagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ReplyDelete
  24. We provide best Selenium training in Bangalore, automation testing with live projects. Cucumber, Java Selenium and Software Testing Training in Bangalore.

    ReplyDelete
  25. Hi This is SRK i'm suggesting you this is app VidMate Apk

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. Thanks for posting this info. I just want to let you know that I just check out your site
    Ryo Hazuki Jacket

    ReplyDelete
  29. Hi , Thank you so much for writing such an informational blog. If you are Searching for latest Jackets, Coats and Vests, for more info click on given link-Puscifer Leather Jacket

    ReplyDelete
  30. Thanks for the best blog. it was very useful for me.keep sharing such ideas in the future as well. Chris Redfield Coat

    ReplyDelete
  31. Emirates ID does lie aged by way of UAE citizens as much a travel record in accordance with a journey inside the GCC Banks and Finance Companies hold taken that a mandatory want in imitation of procedure functions because of savings purposes.
    Emirates ID
    id status

    ReplyDelete
  32. Thanks for submitting a valuable information for us.
    http://ramsol.in/

    ReplyDelete
  33. Thanks for posting this info. I just want to let you know that I just check out your site. Tom Cruise The Mummy Jacket

    ReplyDelete
  34. Such an interesting article here.I was searching for something like that for quite a long time and at last I have found it here. sabrina red coat

    ReplyDelete

  35. It’s clearly an exceptional and very useful fact. Thanks for sharing this helpful data with us. CEA Aviation is one of the Best DGCA Ground Classes in India. It gives admission to all of the aspirants seeking to start with Ground classes. You can enrol for Best Ground training for DGCA checks with us. Once you're clear with DGCA exam Counsellor Desk will assist you in choosing the best flight academy overseas.

    ReplyDelete
  36. Data science is a process of analysing raw data collected from different sources to make useful data; join Data Science Training in Chennai at FITA Academy to learn more about data science.
    Data Science Training in Chennai

    ReplyDelete
  37. The 8171 Ehsaas NADRA Gov Pk program is a commendable initiative that aims to provide financial assistance to those in need, reduce poverty, create employment


    Ehsaas Program Registration online
    8171 Ehsaas Program

    ReplyDelete