Uses of session_id() in PHP

Hi all,
In one of the recent web developer interview, one of them are ask to me “what are the uses of session_id() in php and what are the purpose.”




Session_id() is one of the inbuilt function in PHP. The session_id() will be used to track existence of same user across all the pages of PHP application. The session_id() will be generated whenever the page is calling session_start()function. In realtime example, “Tracking whether same user is navigating from one page to another.”

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




This code is needed to check if session is already started.If session is started, no need to initialize it again. Trying to call session_start(), when session is already initialized will create E_NOTICE error.

session_id() is used to get the session id for the current session or set the session id for the current session. Session variables are set with the PHP global variable: $_SESSION.

session_id() returns the session id for the current session or the empty string (“”). If there is no current session (no current session id exists).

How can I get session id in php and show it?

		session_start();    
		echo session_id();
	




There are two methods are available to use session id and sessions in php

  1. Auto generate the session ID and get it:
  2. 		session_start();
    		$sessionid = session_id();
    	
  3. Set the session ID manually and then start it:
  4. 		session_id( 'sessionId' );
    		session_start();
    	




    If you want to set the session_id() before calling the session_start();.

If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

2 thoughts on “Uses of session_id() in PHP

Leave a Reply

Your email address will not be published.