headers already sent by ... Why my code is not working? [duplicate]
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 se开发者_如何学JAVArver 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
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.
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).
精彩评论