How to get/set session_id() or should it be generated automatically?

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…

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

1 – Auto generate the session ID and get it:

$id = session_id();

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

session_id( 'mySessionId' );

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.

Solution 2

Here you can see it works for me (session is started silently) :

You forgot to start your session, probably

Solution 3

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply