简体   繁体   中英

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

I coded a facebook app in PHP with php-facebook sdk, that is working absolutely fine on my windows 7, wamp.

But, now i implemented it on the webspace running on linux, and i'm getting a session_start() cookie error.

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

I'm not getting why I'm encountering this error.

Below is my code

<!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

 ?>

You cannot print HTML before sending headers, the proper way to do it will be

Example:

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

It's possible that your server needs some ports opened, but it's far more likely that your remote server simply has different error reporting settings than your local development setup. If the Facebook API generates an error, that will be echoed to the page and preempt any headers, including cookies. You can test this by adding @-symbols in front of the Facebook method call, like so:

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

A more robust, more permanent solution is the try {} catch (){} block that Shawn E. Carter suggests. It's my theory that Facebook has been chucking out an error every time, and due to your local configuration you haven't noticed. Fixing the cause of this error should be your priority.

Though i didn't get it, but removing the following lines of code and additional blank line before opening the php tag solved the issue.

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

another way to do it will be like this:

<?php
    ob_start();

?>

<!DOCTYPE html>
<html>
<head>
 <title></title>
<meta></meta>
</head>
<body>

<?php
require 'src/facebook.php';
//YOUR FACEBOOK methods here

?>


</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM