What are the pros and cons of output buffering?

I read on many sites that use

ob_start(); 

can increase page load time because it stores php in a variable and displays it at a time, rather than processing php for a while.

It is also extremely useful for

 header('location: /'); 

Some people say this is spaghetti code, but as long as the code is clear and concise to any programmer, then this should not be a problem, right?

What are your thoughts on its use, and what you set as output buffering, there are pros and cons to how, when and why I should or should not use it.

+7
source share
3 answers

This question contains very good comments on the topic.

+6
source

The main advantage of output buffering is that you can use it with ob_gzhandler, which compresses your output, so you use less bandwidth. Good to use if your server is not configured to send compressed php files.

Another advantage is that your script uses a database or other limited resources, and you have some result before closing your connections or releasing those resources. Instead of having things like this:

  • Database connection
  • Start sending output to user
  • Wait for the user to receive everything
  • Close the database connection

You have:

  • Start buffering
  • Database connection
  • Output some things
  • Close database connection
  • Send the buffer to the user.

When your script needs to be connected to a 100 ms database, and your user needs another 300 to load it, you can understand how output buffering can help remove some restriction on limiting database connections.

I know that something well-encoded using a well-tuned server can negate these advantages, but you never know who will code after you, and you do not always control the server on which it runs.

+1
source

some user does not know php well. therefore they mistakenly use ob_start.

If you use header functions such as header (), cookie (), session, you do not need to send any output. these functions should be used from before exiting.

but some user should stop sending output using the ob_start function or output buffering.

so you can use javascript or meta-forwarding to redirect the user.

 <script language="javascript"> window.location = 'some.php'; </script> 

or you can use meta refresh to redirect the user.

 <META HTTP-EQUIV="Refresh" CONTENT="0;URL=some.php"> 

if you really need to use the header function, you should not send any output (do not forget to enter a character or space or display the signature of UTF-8)

-one
source

All Articles