How to create a session in PHP with a randomized string?
How do I keep session state of a variable throughout a site?
For example:
A user lands on my website, the string generated is
$string = 'uejsh37rhda283jde86541as';
(This string is autogenerated by an xml feed on every page refresh).
Now, everything works so far ok开发者_运维技巧. The problem is when the user clicks on another page on the site, the xml feed creates a new random string.
I know I have to use sessions here, but how exactly?
if(isset($_SESSION[])):
?
else:
?
endif;
Updated code:
if(isset($_SESSION['session'])):
$string = $_SESSION['session'];
else:
$string = $sessionId;
$_SESSION['session'] = $string;
endif;
echo $string;
First of all, you need to call session_start() on all pages that access or manipulate session data.
You can do it like this:
session_start();
if (!isset($_SESSION['string'])) {
$string = makeString();
$_SESSION['string'] = $string;
}
Try this:
// call session_start() here if session handler is not started yet
if (isset($_SESSION['random-string'])) {
$string = $_SESSION['random-string'];
} else {
$string = generateRandomString();
$_SESSION['random-string'] = $string;
}
if (isset($_SESSION['my_string'])) {
$string = $_SESSION['my_string'];
}
else {
$string = generate_random_string();
$_SESSION['my_string'] = $string;
}
// now do something with $string
精彩评论