Home » Php » How can i get session id in php and show it?

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

Posted by: admin April 23, 2020 Leave a comment

Questions:

I need to use some unique id like session id. How can I get session id in php?

How to&Answers:
session_start();    
echo session_id();

Answer:

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.

Answer:

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...";
}
?>

Answer:

You have uniqid function for unique id

You can add prefix to make it more unique

Source : http://pk1.php.net/uniqid

Answer:

if(isset($_POST['submit']))
   {  
 if(!empty($_POST['login_username']) && !empty($_POST['login_password']))
    {
     $uname = $_POST['login_username'];
     $pass = $_POST['login_password'];
     $res="SELECT count(*),uname,role FROM users WHERE uname='$uname' and  password='$pass' ";
$query=mysql_query($res)or die (mysql_error());  

list($result,$uname,$role) = mysql_fetch_row($query);   
$_SESSION['username'] = $uname;
$_SESSION['role'] = $role;
 if(isset($_SESSION['username']) && $_SESSION['role']=="admin")
 {
 if($result>0)
      {
       header ('Location:Dashboard.php');
      }
      else
      {
         header ('Location:loginform.php');
      }
 }

Answer:

In the PHP file first you need to register the session

 <? session_start();
     $_SESSION['id'] = $userData['user_id'];?>

And in each page of your php application you can retrive the session id

 <? session_start()
    id =  $_SESSION['id'];
   ?>