duanchao9559
duanchao9559
2011-08-02 07:58

已经发送的标题...为什么我的代码不起作用? [重复]

已采纳

This question already has an answer here:

I have the following code to get the number of online visitors and members:

session_save_path($_SERVER['DOCUMENT_ROOT'] . '/sessions/' . (isset($_COOKIE['uid']) ? "members/" : "guests/"));
if(isset($_COOKIE['uid'])){
    session_id($_COOKIE['uid']);
}
session_start();
define("MAX_IDLE_TIME", 15);
$online_guests = 0;
$directory = opendir($_SERVER['DOCUMENT_ROOT'] . '/sessions/guests/');
while(false !== ($file = readdir($directory))){
    $online_guests++;
}
$online_guests -= 2;
$online_members = array();
$directory = opendir($_SERVER['DOCUMENT_ROOT'] . '/sessions/members/');
while(false !== ($file = readdir($directory))){
    if($file != '.' && $file != '..'){
        $online_members[] = intval(substr($file,5));
    }
}

I tested the code from my wamp server and it worked, but when I uploaded the code to my host it gives me the following error:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/csabi/public_html/index.php:9) in /home/csabi/public_html/track-online-users.php on line 6

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doukun1450 doukun1450 10年前

    That message means your program had some output before you called session_start. You can't send anything to the browser before that since setting the session cookie has to happen in the HTTP headers, which come before the response body.

    If both index.php and track-online-users.php are the same on both servers, check for blank lines before the opening <?php in both files, byte-order-marks at the start of the file, etc.

    点赞 评论 复制链接分享
  • duaeim2874 duaeim2874 10年前

    As an alternative to removing any blank space, ... you could use output buffering. This will stop any content being sent to the user untill it gets to the end of the script. It will then flush the contents of the buffer to the user. To start output buffering, just write ob_start(); at the beginning of your file, before any blank spaces, text, ...

    Not that it's wrong to remove any blank space, but it's always useful to know.

    P.S.: To flush the contents of the buffer before the end of the script, you can use ob_flush();, or ob_end_flush(); (which will also end the buffering).

    点赞 评论 复制链接分享