问题
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!
回答1:
The general principle is you cannot use echo
before header()
. So, this will never work:
echo "this is my header";
header("Location: account.php");
echo "this is my footer";
However, if you sent the headers first, everything works fine:
header("Location: account.php");
echo "this is my header";
echo "this is my footer";
In your case, you should do the check before you include the header:
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.
回答2:
ob_start()
captures the output (what would otherwise be printed or echoed). If you don't need to echo the output or to do anything with it then just use ob_end_flush()
when you are finished.
来源:https://stackoverflow.com/questions/19139521/php-should-i-use-ob-clean-after-ob-start