php - Singleton session problem

179

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;
    }
}
477

Answer

Solution:

You can't output any data before callingsession_start(). Make sure there are no echos or prints or anything that spits out data before you instantiate that class.

825

Answer

Solution:

Maybe this will help...

http://php.net/manual/en/function.session-start.php

For the error: 

Warning: session_start(): Cannot send session cache limiter - headers already sent ... 

this kind of errors would occur, when the encoding of your script file needs to send some headers just after your script starts to execute, 

this happens mostly with the scripts using normal utf8 encoding. 

To overcome the issue, use utf8(without BOM) encoding provided by notepad++ and most modern editors. Using utf8 encoding and cookie based sessions, will result in headers already sent by error.
155

Answer

Solution:

The problem withheaders already sent errors is that you've sent some body content, html, maybe whitespace, ... This Problem can be removed using two ways.

  1. Let the creation of theSession be one of the first things of your script - before any output operation through callingSession::instance() in the beginning.

  2. Use output buffering. The first instruction should beob_start() and the lastob_end_flush().

People are also looking for solutions to the problem: php - Best way to store many ip ranges?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.