3

I made a simple login-system in php and mysql, but I keep getting errors saying that headers already been sent, and using ob_start fixes this problem, but im not sure if I should then use ob_clean at the footer afterward?

Also, the error comes when I have logged in to the account page, saying header already been sent in previuos page - > header("Location: account.php"); But I have to redirect the user when they login.

My login page looks like this

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.

This code above works if I use ob_start in the header.php file. But should I use ob_clean afterwards in the footer.php file?

Sorry if anything is unclear, english is not my first languish

Thanks!

4

2 回答 2

3

一般原则是你不能使用echobefore header()。所以,这永远不会奏效:

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.
于 2013-10-02T14:37:58.547 回答
1

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

于 2013-10-02T14:38:08.577 回答