php - Singleton session problem
probably a quick fix but can't figure out where I'm going wrong. I'm setting up a simple singleton Session class, but I'm getting the following error, so i'm obviously not setting things up correctly:
Am I making an obvious mistake here? Thanks for any help
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent...
class Session {
// Session singleton
protected static $instance;
private function __construct()
{
//start the session
session_start();
Session::$instance = $this;
}
public static function instance()
{
if (Session::$instance === NULL)
{
// Create a new instance
new Session;
}
return Session::$instance;
}
}
Answer
Solution:
You can't output any data before calling
session_start()
. Make sure there are no echos or prints or anything that spits out data before you instantiate that class.Answer
Solution:
Maybe this will help...
http://php.net/manual/en/function.session-start.php
Answer
Solution:
The problem with
headers already sent
errors is that you've sent some body content, html, maybe whitespace, ... This Problem can be removed using two ways.Let the creation of the
Session
be one of the first things of your script - before any output operation through callingSession::instance()
in the beginning.Use output buffering. The first instruction should be
ob_start()
and the lastob_end_flush()
.