How can I get session id in php and show it?
session_start();
echo session_id();
Before getting a session id you need to start a session and that is done by using: session_start() function.
Now that you have started a session you can get a session id by using: session_id().
/* A small piece of code for setting, displaying and destroying session in PHP */
<?php
session_start();
$r=session_id();
/* SOME PIECE OF CODE TO AUTHENTICATE THE USER, MOSTLY SQL QUERY... */
/* now registering a session for an authenticated user */
$_SESSION['username']=$username;
/* now displaying the session id..... */
echo "the session id id: ".$r;
echo " and the session has been registered for: ".$_SESSION['username'];
/* now destroying the session id */
if(isset($_SESSION['username']))
{
$_SESSION=array();
unset($_SESSION);
session_destroy();
echo "session destroyed...";
}
?>
I would not recommend you to start session just to get some unique id. Instead, use such things as uniqid()
because it's intended to return unique id.
However, if you already have session, then, of course, use session_id()
to get your session id - but do not rely on that, because "unique id" isn't same as "session id" in common sense: for example, multiple tabs in most browsers will use same process, thus, use same session identifier in result - and, therefore, different connections will have same id. It's your decision about desired behavior, I've mentioned this just to show the difference between session id and unique id.
You have uniqid function for unique id
You can add prefix to make it more unique
Source : http://pk1.php.net/uniqid