PHP 标头重定向
我有一个登录类,用户登录到数据库,然后我希望该方法将用户重定向到他们自己的个人资料页面。我希望使用 header() 重定向,尽管我在实现它时遇到了一些问题。
因为我想在 HTMl 启动后调用 header() ,所以它不会重定向,有没有什么巧妙的方法将其包装到函数中并在需要时调用它?
I have a login class, whereby a user logs into the database then I want the method to redirect the user to their own profile page. I was hoping to use header() redirect although I've been having a few issues implementing it.
Because I want to call the header() after the HTMl has been started it won't re-direct, is there any neat way to wrap it into a function and call it when I need it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两种方法:
重新组织脚本以首先执行逻辑(包括
header()
重定向),然后输出 HTML。-或-
缓冲您的 HTML 输出,并仅在您的逻辑确定不需要重定向后发送缓冲区内容。
第一种方法是优选的。逻辑应尽可能与布局分开。您可以考虑实现 MVC(模型、视图、控制器)模式来提高代码的可维护性。
Two ways:
Reorganize your script to perform logic first (including the
header()
redirect) and output HTML second.-or-
Buffer your HTML output and send the buffer contents only after your logic determines that the redirect is not needed.
The first method is preferable. Logic should be separated from layout wherever possible. You may consider implementing the MVC (Model, View, Controller) pattern to improve the maintainability of your code.
您应该在输出任何 HTML 之前完成所有逻辑。不要在页面中间检查是否需要重定向。
否则,您可以启用输出缓冲,但我不会依赖它。
You should do all of your logic before you output any HTML. Don't check whether or not you need to redirect in the middle of your page.
Otherwise, you could enable output buffering, but I wouldn't rely on it.
如果您想包含 header() 重定向方法,则代码必须位于任何 html 标记之前,但是您可以创建一个函数,使其行为类似于 header(),例如
,然后调用该函数,
该函数将在 3 秒内重定向到 google.com。
if you want to include header() redirect method then the code must come before any html tag, however you can make a function to behave like header() for example
then call the function like
which will redirect to google.com in 3 seconds.