1)

if(session_id() == "")
{
session_start();
}

2)

<?php
function start_session(){
static $started=false;
if(!$started){
session_start();
$started = true;
}
}
?>

3)

if (!isset ($_SESSION)) session_start();

These are three samples to avoid start session multiple times. It seems to me that the approach 3) is the best.

I would use approach 3), any advices on this issue? Will approach 1) or 2 be the best to use?

Thanks!

    //sessions.php
    if(!defined(SESSIONS)){
     session_start();
     define('SESSIONS', TRUE);
    }
    //index.php
    require_once('sessions.php');
    echo 'Hi';
    //include does nothing
    include('sessions.php');

      why not use this?

      if (!isset ($_SESSION)) session_start();

      or

      if(session_id() == "") session_start();

      This will cover all the multiple session_start(). This is simple enough. I can mass replace all the old scripts session_start() with the above codes and solve the problem.

      Or the above two codes have some problems?

        I think it might be better to use simple class with singleton pattern 🙂

        class mySession
        {
          private static $oInstance=null;
        
          public static function getInstance()
          {
            if(self::$oInstance==null)
            {
               self::$oInstance==&new self();
            }
            return self::$oInstance;
          }
        
          private function __construct()
          { 
           session_start();
          }
        
          public function __set($name,$value)
          {
            $_SESSION[$name]=$value;
          }
        
          public function __get($name)
          {
             return isset($_SESSION[$name]) ? $_SESSION[$name] : null ;
          }
        }
        

        That is very simple example but u can fit this simple class to your needs 🙂

          Write a Reply...