【问题标题】:ob_start() and ob_implicit_flush(true) using at the same time cause an issueob_start() 和 ob_implicit_flush(true) 同时使用会导致问题
【发布时间】:2018-08-07 11:49:23
【问题描述】:
我需要在执行 php 文件时回显一些输出,因为执行需要 10 秒,并且 10 秒页面的结尾应该通过header("Location:test.php) 定向
但是如果我同时使用 ob_start 和 ob_implicit_flush(true) ,我们不能直接页面和获取
警告:无法修改标头信息 - 标头已由
发送
我还需要在执行时使用 ob_implicit_flush(true) 来打印输出。
如何显示输出和直接页面?
【问题讨论】:
标签:
php
header
flush
ob-start
【解决方案1】:
您不能在同一响应中同时输出正文内容 和重定向标题,更不用说输出body before 标题。 HTTP 标头首先出现,因此您不能在标头之前输出正文,也不能在输出正文之后输出标头。此外,重定向标头会导致请求在浏览器显示其任何内容之前立即被重定向,因此整个事情在两个级别上都不起作用。
如果您想在服务器执行某些操作时显示任何内容,则需要以某种形式使用 Javascript。
【解决方案2】:
如果你使用 header() 函数,它之前必须没有输出。不过当然可以在使用函数之后。
ob_start 启动缓冲区工作,而 ob_implicit_flush 告诉根本不使用缓冲区。所以这两个功能不能这样组合。
例子:
ob_start(); //set buffer on
print('Hello World'); //no output since buffer on
ob_implicit_flush(true); //buffer switched off again
print('Test'); //prints 'Hello World' and 'Test'
header('Location: ...'); //ERROR: output already done
您现在必须决定是要从脚本中输出信息还是进行重定向。
在标头之后输出一些内容是可能的,但它没有任何意义,因为你不会再看到它了。
也许你可以使用 ob_get_length() 函数来检查是否有输出,然后决定是切换页面还是输出缓冲区:
ob_start(); //set buffer on
print('Hello World'); //no output since buffer on
if(ob_get_length() > 0)
ob_end_flush();
else
header('Location: ...'); //will not be executed if output was generated