What are the pros and cons of output buffering? [duplicate]
I have read on many websites that using
ob_start();
can enhance your page load times, as it stores the php in a variable and displays it in one go rather than processing the php a bit of a time.
Also it is extremely useful for
header('location: /');
Some people say that 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 to using it, and wh开发者_StackOverflow中文版at do you set as your output buffering, are there pros and cons to how, when and why I should or shouldn't use it.
The main advantage of output buffering is that you can use it with the ob_gzhandler which will compress your output so you use less bandwidth. Good to use if your server is not setup to send php files compressed.
Another advantage is if your script uses a database or other constrained resources and you have some output before closing your connections or releasing those resources. Instead of having this kind of thing:
- Connect to database
- Start sending output to the user
- Wait for the user to receive everything
- Close the database connection
You have:
- Start buffering
- Connect to database
- Output some things
- Close database connection
- Send the buffer to the user.
When your script would need to be connected for 100ms to the database and your user need 300 more to download it, you can understand how output buffering can help releasing some stress on the database connections limit.
I know something coded well using a well configured server could nullify those advantages, but you never know who will code after you and you don't always have control of the server it's running on.
some user dont know php well. so they use ob_start wrongly.
if you are using header functions such as header(), cookie(), session you dont have to send any output. these function have to use from before output.
but some user is to stop sending output using ob_start or output buffering function.
so you could use javascript or meta forwading to forward user.
<script language="javascript"> window.location = 'some.php'; </script>
or you could use meta refresh to forward user.
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=some.php">
if you really need to use header function you must dont send any output(dont forget that enter character or space is or UTF-8 signature is output too)
精彩评论