【问题标题】:PHP Should I use ob_clean after ob_startPHP 我应该在 ob_start 之后使用 ob_clean
【发布时间】:2013-10-08 23:46:05
【问题描述】:

我在 php 和 mysql 中创建了一个简单的登录系统,但我不断收到错误消息,提示标头已经发送,使用 ob_start 解决了这个问题,但我不确定我是否应该在之后在页脚使用 ob_clean?

另外,当我登录到帐户页面时出现错误,说标题已在上一个页面中发送 - > header("Location: account.php");但是我必须在用户登录时重定向用户。

我的登录页面是这样的

require_once('models/init.php');  // db connection and other functions
include('header.php');  // some html code for the header, with one line php-function to check if user is logged in, if so show "home" tab instead of "login"


{ 

  php code to check if username/pass matches etc, and if so redirect to account page

  header("Location: account.php");

}

 echo "<form>" // display the login form

include("footer"); // including footer, some html/js code.

如果我在 header.php 文件中使用 ob_start,则上面的代码有效。但是之后我应该在 footer.php 文件中使用 ob_clean 吗?

对不起,如果有什么不清楚的地方,英语不是我的第一次萎靡

谢谢!

【问题讨论】:

  • 为什么不把登录检查放在header.php 包含上面?
  • 这是我尝试的第一件事,但我仍然收到错误消息,提示标题已输出。此外,如果我这样做,ob_start 即使在那时也能解决问题
  • 不,最佳做法是删除 header() 之前的空格。
  • 谢谢 我会记住这一点,但是当使用 ob_start 时,我应该在之后使用 ob_clean 例如在页脚中吗?手册对我来说似乎有点不清楚,这就是我问的原因

标签: php mysql header ob-start


【解决方案1】:

一般原则是你不能在header()之前使用echo。所以,这永远行不通:

echo "this is my header";
header("Location: account.php");
echo "this is my footer";

但是,如果您先发送标头,则一切正常:

header("Location: account.php");
echo "this is my header";
echo "this is my footer";

在您的情况下,您应该在包含标题之前进行检查:

require_once('models/init.php');  // db connection and other functions

if ($user_is_logged_in) { // Do your check here
    header("Location: account.php");
}

include('header.php');  // some html code for the header, with one line php-function to check if user is logged in, if so show "home" tab instead of "login"
echo "<form>" // display the login form
include("footer"); // including footer, some html/js code.

【讨论】:

  • 这就是我要做的,如果你仍然得到错误,确保第一个&lt;?php之前没有空格并检查utf-8 BOMs
  • 感谢您让我这么清楚,“不要在 header() 之前使用 echo”在 header.php 文件中,我有一个 if(!isUserLoggedIn()) echo this else echo that。跨度>
  • 也会接受你的回答,它说我要等到 4 分钟才能完成
【解决方案2】:

ob_start() 捕获输出(否则会被打印或回显)。如果您不需要回显输出或对其执行任何操作,则只需在完成后使用ob_end_flush()

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 2019-01-31
    • 2015-05-09
    • 1970-01-01
    • 2015-08-10
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多