2013-10-02 22 views
3

我在php和mysql中做了一个简单的登录系统,但是我一直收到错误,说已经发送了头文件,并且使用ob_start修复了这个问题,但是我不知道是否应该使用ob_clean在页脚之后?此外,当我登录帐户页面时说错误出现,说头已经在previuos页面发送 - > header(“Location:account.php”);但是我必须在用户登录时重定向用户。PHP我应该在ob_start后使用ob_clean

我的登录页面看起来像这样

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吗?

很抱歉,如果有不清楚的地方,英语不是我的第一憔悴

谢谢!

+0

为什么不把登录检查放在'header.php'上面? –

+0

这是我尝试的第一件事,但我仍然得到一个错误,表示头文件已经输出。另外,如果我这样做,ob_start即使解决了问题 –

+0

不,最好的做法是删除'header()'之前的空格。 – George

回答

3

一般原则是你不能在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. 
+0

这就是我要做的,如果你仍然得到错误,确保在第一个<?php'之前没有空格并且检查[utf- 8'BOM's](http://stackoverflow.com/questions/2223882/whats-different-between-utf-8-and-utf-8-without-bom) –

+0

谢谢你对我这么清楚,“不要在header()之前使用echo()“ 在header.php文件中,我有一个if(!isUserLoggedIn())echo this else echo that。 –

+0

也会接受你的答案,它说我不能做到4分钟 –

1

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