Search code examples
phpfilesessionfront-controller

two session_starts() hang PHP app


Context: I was going to build app using mod_rewrite (front page loading child pages), but got stuck on loading session_enabled pages from the front controller page.

Problem: The problem is that I use session_start() call twise, PHP page stops responding. Which is strange, the session_start function is harmless and they are called on different pages.

I've narrowed down the problem to this sample:

child.php file:

parent.php file:

Call to parent.php will make browser load infinitely. As soon as you comment one of session_start() calls - it loads instantly.

What is the source of the problem? I badly need session-enabled pages.

PS I can work it around by including pages, but they rely on URL params, I would like to avoid fixing them for sake of some kind of parameter proxies.


Solution

  • Besides that only one session can be used at a time. You need to call the session_regenerate_id function to generate a new ID:

    if (session_id() != '') {
        session_write_close();
    }
    session_start();
    session_regenerate_id();
    

    Otherwise the parent’s session ID would also be used for the child’s session.