AlexA
AlexA

Reputation: 4118

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.

Upvotes: 0

Views: 523

Answers (5)

Gumbo
Gumbo

Reputation: 655219

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.

Upvotes: 1

Tom Haigh
Tom Haigh

Reputation: 57815

You need to call session_write_close() once you no longer need to write to the session. Currently as both your scripts have the session open for their entire duration, you will only be able to have one running at a time.

From the manual:

Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

Upvotes: 4

jeroen
jeroen

Reputation: 91734

You can also check if a session is already started and only start a new one if not:

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

Upvotes: 1

kmkaplan
kmkaplan

Reputation: 18960

Try using session_write_close() before loading your child page.

Upvotes: 1

Bart S.
Bart S.

Reputation: 11507

Having two session_starts() in your script is a bad thing anyway.

Why don't you just start the session on your parent.php file (and not child.php)? Or just child.php and not parent.php

It's a good idea to have one page that is included by all other pages that initializes everything (SQL connect, session start, etc). And then include that page on all others.

Upvotes: 0

Related Questions