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..
<?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'];
}
?>
2
Answers
try this code:
This will keep the unique session even you visit the first page again.