Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set generated string as a unique session key?

I have a website that creates a session when a user logs in, but the sessions are just the email & username, which works fine for customers that create an account, but I want to generate a unique session key for users that dont want to signup/login, the reason is because currently if a user is not logged in and they add an item to the checkout page, the item will be visible to every customer who is not logged in, so I would like to create a session based on a unique string so that there are no conflicts for customers who dont want to signup/sign-in.

The problem is that when I redirect to the test.php page it cant find the session key.

Here is my session file that generates the unique key..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?php
 session_start();

 $_SESSION['sessionKey'] = $randomString;

 if(!isset($_SESSION['sessionKey']))
 {

 function generateRandomString($length = 64) {
   $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $charactersLength = strlen($characters);
   $randomString = '';
   for ($i = 0; $i < $length; $i++) {
      $randomString .= $characters[rand(0, $charactersLength - 1)];
   }
   return $randomString;
   }
   echo generateRandomString();
   }
   ?>

   <br><br>
   <a href="test.php">Go to test page</a>

and then my test.php page…

<?php
 session_start();

 if(!isset($_SESSION['sessionKey']))
 {
  echo "cant find unique session key";
 } else {
  echo $_SESSION['sessionKey'];
 }
 ?>

>Solution :

This will keep the unique session even you visit the first page again.

session_start();

 if(!isset($_SESSION['sessionKey']))  {
    $_SESSION['sessionKey'] = generateRandomString();
   }

function generateRandomString($length = 64) {
   $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $charactersLength = strlen($characters);
   $randomString = '';
   for ($i = 0; $i < $length; $i++) {
      $randomString .= $characters[rand(0, $charactersLength - 1)];
   }
   return $randomString;
}

echo $_SESSION['sessionKey'];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading