1

I have the following in my PHP header from an existing little web app. My question is: doesn't this make the page jump through an extra step to first check and then start a session? What is the point of this?

If a session exists, can't I just use session_start and if it does not won't it be ignored?

PHP

if (!isset($_SESSION)) {
   session_start();
}
2
  • So you don't do too much work by starting the session 10.000 times by accident. Commented Aug 8, 2013 at 13:58
  • 2
    Kind of strange, but it depends on where it is. If it's in a function, for instance, or a file that is likely to be included in multiple places, then like Tdelang said, it's so you don't start a session when it's already started. In fact it's more than just saving time: I think if you call session_start() when there's already an existing session, it will replace that session. If it's in a place where it is only going to be called once, then it seems superfluous, but doesn't do any harm. Commented Aug 8, 2013 at 14:01

2 Answers 2

5

If you call session_start() and no session exists it will create a new session. If there is an existing session it will resume that.

Sign up to request clarification or add additional context in comments.

Comments

3

If I'm not mistaken, the $_SESSION superglobal will always exist, so your code won't really do very much anyway.

If you're on PHP <5.4, use the following code instead:

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

On PHP 5.4+, use this:

if(session_status() != PHP_SESSION_ACTIVE) {
    session_start();
}

You should only really be calling session_start() once, but as @ScottHelme said, calling it multiple times will not have a negative effect, the session will be either created or resumed every time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.