7

I have some basic session handling in my application. In each page I check if the user is logged in. If they are then they're already identified by $_SESSION['user_id'], and their login/logout is recorded in a MySQL table.

I would also like to record visits by guests (not logged in) based on a unique id. I had assumed that once session_start() is called that an internal session_id is automatically generated and that calling session_id() I could retrieve this. But this just gives an "undefined variable" error, so I guess I have to set it manually..? If so then what's the best way so that it will be a unique ID, or what is the usual method?

Thanks for any help...

Michel
  • 490
  • 4
  • 11
questioner
  • 1,144
  • 4
  • 14
  • 22

3 Answers3

39

There are 2 ways to use sessions and session id's in PHP:

1 - Auto generate the session ID and get it:

session_start();
$id = session_id();

2 - Set the session ID manually and then start it:

session_id( 'mySessionId' );
session_start();

If you intend to set the session ID, you must set it before calling session_start(); If you intend to generate a random session_id (or continue one already started in a previous page request) and then get that id for use elsewhere, you must call session_start() before attempting to use session_id() to retrieve the session ID.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
Brian
  • 3,013
  • 19
  • 27
1

Here you can see it works for me (session is started silently) : http://sandbox.phpcode.eu/g/f6b6b.php

You forgot to start your session, probably

genesis
  • 50,477
  • 20
  • 96
  • 125
  • Yeah I just tried it on a test page and it works as you suggest. But in my app I'm using a class for my sessions, and only calling session_start() once from within the constructor. So the problem seems to be only with getting/setting session_id() in a class method, but no problem setting/getting vars in the $_SESSION array.. Thanks though, I didn't know about it starting silently. – questioner Aug 15 '11 at 18:46
  • @grainne: nonono, you didn't get me. It's my sandbox's behavior - session is started automatically, so you can't see it inside "show code", you have to `session_start()` first and after that, you can use `session_id()` – genesis Aug 15 '11 at 19:18
  • Thanks for explaining. I get what you're saying now, first time I thought it was just some pasted code. Not sure what was happening for me then :/ I'll have to do some proper testing of all this later... – questioner Aug 15 '11 at 19:51
0

Well, it may be a little bit strange, but when I need unique ID I use uniqid()

Nausik
  • 735
  • 8
  • 22
  • Didn't know about this :) I think what I'll do then is just use something like $_SESSION['guest_id'] with uniquid, as session_id() isn't working for whatever reason! – questioner Aug 15 '11 at 18:49