facebook.php错误-sesion_start()-标头已发送


facebook.php error - session_start() - Header already sent

我用PHP和facebook-sdk用PHP编写了一个facebook应用程序,它在我的windows7,wamp上运行得非常好。

但是,现在我在linux上运行的webspace上实现了它,并且收到了session_start()cookie错误。

Warning: session_start() [function.session-start]: Cannot send session cookie - 
headers already sent by (output started at /mydirectory/index.php:5) in 
/mydirectory/src/facebook.php on line 37

我不明白为什么会遇到这个错误。

下面是我的代码

<!DOCTYPE html PUBLIC  
"-//W3C//DTD XHTML 1.0 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
    require_once('src/facebook.php');
    $app_id = "MY_APP_ID";
    $app_secret = "MY_APP_SECRET";
    $config = array(
    'appId' => $app_id,
    'secret' => $app_secret,
    'fileUpload' => true,  
    'cookie' => true
    );
    $facebook = new Facebook($config);
    $user_id = $facebook->getUser();
 // other content
 ?>

在发送标题之前不能打印HTML,正确的方法是

示例:

<?php
session_start();
//
require 'src/facebook.php';
$facebook = new Facebook(array(
  'appId'  => '135669679827333',
  'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxx',
  'cookie' => true, // enable optional cookie support
  ));
  try { $user = $facebook->getUser(); } catch (FacebookApiException $e) {  }
?>
<!DOCTYPE html>
<html>
<head><title></title>
<meta />
</head>
<body>
<content here>
</body>
</html>

您的服务器可能需要打开一些端口,但更可能的是,您的远程服务器的错误报告设置与本地开发设置不同。如果Facebook API生成错误,则该错误将被回显到页面并抢占包括cookie在内的任何头部。你可以通过在Facebook方法调用前添加@-符号来测试这一点,比如:

$facebook = new Facebook($config);
$user_id = @$facebook->getUser();

Shawn E.Carter提出的try {} catch (){}块是一个更稳健、更持久的解决方案。我的理论是,Facebook每次都会抛出一个错误,而且由于您的本地配置,您没有注意到。修复此错误的原因应该是您的首要任务。

虽然我没有得到它,但在打开php标记之前删除以下代码行和额外的空白行解决了问题。

<!DOCTYPE html PUBLIC  
 "-//W3C//DTD XHTML 1.0 Transitional//EN"  
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

另一种方法如下:

<?php
    ob_start();
?>
<!DOCTYPE html>
<html>
<head>
 <title></title>
<meta></meta>
</head>
<body>
<?php
require 'src/facebook.php';
//YOUR FACEBOOK methods here
?>

</body>
</html>