The Codesee The Codesee - 5 months ago 18
PHP Question

Random string saved as session regenerates on page refresh

I am generating five random characters using the

uniqid
function and saving it as a session as I need to retain it (keep it) when the page refreshes due to a form being submitted.

The only problem is... each time the page is refreshed (due to the form being submitted) a new set of five random characters are generated!

<?php
$_SESSION['string'] = substr(uniqid('', true), -5);
echo $_SESSION['string'];
?>

<form method="post">
<input type="submit">
</form>


Note: I cannot include the characters in a URL variable and cannot show the characters to the user other than when I do in the code above (this rules out the option of placing the characters in a hidden input element).

Answer

Use isset:

<?php
session_start();
if(!isset($_SESSION['string']))
{
  $_SESSION['string'] = substr(uniqid('', true), -5);
}
echo $_SESSION['string'];
?>