javascript 发送标头后PHP重定向?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3954257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP redirect AFTER sending headers?
提问by Piskvor left the building
I have a function which needs to redirect the page if a variable is set etc...
如果设置了变量等,我有一个函数需要重定向页面...
The problem is, this function is at the bottom of the php page.
问题是,这个函数在php页面的底部。
This means, I have outputted alot of information, so I get a headers warning.
这意味着,我已经输出了很多信息,所以我收到了标题警告。
"Warning - Headers already sent by ..."
“警告 - 标题已经由...发送”
Is there any way to redirect after headers are sent?
发送标头后有什么方法可以重定向吗?
Thanks
谢谢
回答by damusnet
What you should do is put ob_start()at the very beginning of your page, and ob_flush()at the very end. This way you don't run into headers already sent errors.
您应该做的是放在ob_start()页面的最开始和ob_flush()最后。这样你就不会遇到标题已经发送的错误。
See those functionsfor further reference.
请参阅这些函数以获取进一步参考。
回答by Piskvor left the building
There are ways, but they're basically workarounds:
有一些方法,但它们基本上是解决方法:
The simplest one is the meta http-equiv:
最简单的一种是meta http-equiv:
<meta http-equiv="Refresh" content="0;http://www.example.com/newlocation">
- some browsers will not like this when it's outside of the
<head>element, and drop into quirks mode
- 当它在
<head>元素之外时,一些浏览器不会喜欢这个,并进入怪癖模式
Or, you can try the JavaScript redirect:
或者,您可以尝试 JavaScript 重定向:
<script>
window.location = 'http://www.example.com/newlocation';
</script>
- which obviously won't work without JavaScript.
- 如果没有 JavaScript,这显然是行不通的。

