Thursday, 10 March 2016

How to stop uniqid() from regenerating in a PHP form

I want to generate a random key for the user to use during registration. The code compares the generated key with the user input but the key gets regenerated when the user submits the form, so they are never the same. I tried to protect the generator function by checking if it was already generated but it didn't work. Then, I tried to use session as well, which didn't work either. Here's the code which always produces "fail" rather than "success":



Edit: I made some corrections according to your comments.



session_start();
$_SESSION['key'] = randomKey();
$key1 = $_SESSION['key'];

error_reporting(E_ALL);
ini_set('display_errors', 1);

function randomKey() {

if (empty($_SESSION['key'])) {
$key = uniqid();
$_SESSION['key'] = $key;
return $key;
} else {

return $_SESSION['key'];
}
}

if(isset($_POST['submit']))
{
$input = $_POST['inputKey'];
if (strcmp($input,$_SESSION['key']) == 0) {
echo 'success';
} else {

echo 'fail';
}
}
?>


















Your key:


Enter your key:




No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...