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';
}

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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)

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.