Jump to content

checking if a session exists before session_start()


play_

Recommended Posts

I usually have session_start() in the header of my sites, causing a session to start even when the visitor enters it for the first time.

that's unnecessary though and i'd like to start a session only if there actually is one present.

 

Any way to do this?

 

I thought something like this might've worked, but it doesn't:

if(session_id() != "") {
session_start();
echo 'There is a session_id, start session';
} else {
    echo 'no session_id exists. session not started - unnecessary';
}

causing a session to start even when the visitor enters it for the first time

 

A session isn't going to start unless you actually register one. session_start() doesn't "create" any sessions. So calling session_start on your header page isn't a bad thing.

 

If you really want to do that, just do this

 

<?php

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

?>

 

Now session_start will only be called if the user has a registered session.

Exactly what i want to do.

 

every page is in the following structure:

 

header

content/body

footer

 

header and footer are includes in every page.

 

currently i have session_start() at the top of the header, which causes a session to start even if a user enters the site for the first time.

 

I want a session to start only if the user logs in. (or if i need to display a session variable here and there, such as the user's first name. but this isnt' related to the question)

You should be able to put....

 

<?php

  if (!empty(session_id()) {
    session_start();
  }

?>

 

In your header. And also call session_start() just prior to loging in (when your first set variables in the $_SESSION array).

 

I just fail to see the point.

Have you ever visited a website for the first time in that day, and when you click on the first link, you see the session id in the url?

i'd like that not to happen.

 

and with this, it will not start a session unless it's required.

 

thank you

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.