This question already has an answer here:
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":
<?php
session_start();
$key1 = randomKey();
function randomKey() {
static $key;
if (!isset($_SESSION['key'])) {
$key = uniqid();
$_session['key'] = $key;
return $key;
} else {
return $_session['key'];
}
}
if(isset($_POST['submit']))
{
$inputKey = $_POST['inputKey'];
if (strcmp($inputKey,$key1) == 0) {
echo 'success';
} else {
echo 'fail';
}
}
?>
<html>
<head>
</head>
<body>
<table border="0">
<form method="POST" action="">
<tr>
<td>Your key:</td>
<td>
<b>
<?php echo $key1; ?></b>
</td>
</tr>
<tr>
<td>Enter your key:</td><td><input type="text" name="inputKey"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</form>
</table>
</body>
</html>
I have also tried few other alternatives. For example, I tried comparing the two strings by using if ($inputKey === $key1) and changed form action to action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>".
Here's the randomKey() function, without session:
function randomKey() {
static $key;
if ($key == null) {
$key = uniqid();
return $key;
} else {
return $key;
}
}
How can I stop the key from regenerating or compare the input with the previously generated key? Thank you.
Aucun commentaire:
Enregistrer un commentaire