输出缓冲的优点和缺点是什么?
我在许多网站上读到,使用
ob_start();
可以提高页面加载时间,因为它将 php 存储在变量中并一次性显示它,而不是一次处理 php 一点。
它也非常有用,
header('location: /');
有些人说这是意大利面条代码,但只要代码对任何程序员来说都清晰简洁,那么这应该不是问题,对吧?
您对使用它的想法是什么,您将什么设置为输出缓冲,对于如何、何时以及为什么我应该或不应该使用它有优点和缺点。
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 what do you set as your output buffering, are there pros and cons to how, when and why I should or shouldn't use it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输出缓冲的主要优点是您可以将其与 ob_gzhandler 一起使用,它将压缩您的输出,从而使用更少的带宽。如果您的服务器未设置发送压缩的 php 文件,则非常适合使用。
另一个优点是,如果您的脚本使用数据库或其他受限资源,并且在关闭连接或释放这些资源之前您有一些输出。而不是这样的事情:
您必须:
当您的脚本需要连接到数据库 100 毫秒,而您的用户还需要 300 毫秒才能下载它时,您可以了解输出缓冲如何帮助释放数据库连接限制的压力。
我知道使用配置良好的服务器编写的代码可能会抵消这些优势,但你永远不知道谁会在你之后编写代码,而且你并不总是能够控制它运行的服务器。
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:
You have:
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.
有些用户不太了解 php。所以他们错误地使用了 ob_start 。
如果您使用 header()、cookie()、session 等标头函数,则无需发送任何输出。这些函数必须在输出之前使用。
但有些用户使用 ob_start 或输出缓冲函数停止发送输出。
所以你可以使用 javascript 或元转发来转发用户。
或者您可以使用元刷新来转发用户。
如果你确实需要使用标头功能,你一定不要发送任何输出(不要忘记输入字符或空格或UTF-8签名也被输出)
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.
or you could use meta refresh to forward user.
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)