2

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

VolkerK
  • 95,432
  • 20
  • 163
  • 226
Csabi
  • 661
  • 10
  • 20

2 Answers2

4

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.

Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
  • Yes, you are right! Thanks! In the index.php file the track-online-users was included only after the page title. – Csabi Aug 02 '11 at 08:05
  • But i have one more question: why the same script was working from my computer on wamp server ? – Csabi Aug 02 '11 at 08:05
  • @user: Your own server may be configured to always use output buffering. Check your configuration. – Kerrek SB Aug 02 '11 at 08:07
0

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).

Sean Bone
  • 3,368
  • 7
  • 31
  • 47