Safe Session Start With no Errors

suggest change

Many developers hit this problem on large projects, especially modular CMSs with plugins, addons, and components. Here is a solution for a safe session start: it checks the PHP version, then checks whether a session is already started. If no session exists, it starts one. If a session exists, nothing happens. With read_and_close (PHP 7.0 and later), session_start() reads the session and closes it immediately, so later writes to $_SESSION are not saved.

if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
    if(session_status() == PHP_SESSION_NONE) {
        session_start(array(
          'cache_limiter' => 'private',
          'read_and_close' => true,
       ));
    }
}
else if (version_compare(PHP_VERSION, '5.4.0') >= 0)
{
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
}
else
{
    if(session_id() == '') {
        session_start();
    }
}

This can help you a lot to avoid session_start error.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents