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.
<?php
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';
}
}
?>
<html>
<head>
</head>
<body>
<form method="POST" action="">
<table border="0">
<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>
</table>
</form>
</body>
</html>