samedi 2 avril 2016

PHP: A different random string is generated every time I use the same variable

I'm trying to generate a random string and insert it into a database showing the user that same random string. However, every time I use that variable that contains the random string, its value is changed to a new random string. As a result, the user sees a different random string than the one inserted into the database.

This is at the top of my PHP code:

$token = GenerateRandomString();

This happens when the user submits a form:

$query = "INSERT INTO mytable (token) VALUES ('{$token}')";
$result = mysqli_query($connection, $query);

This is how I show the user the random string generated:

<input type="hidden" name="mytoken" id="mytoken" value="<?php echo $token; ?>" />

This is the function used to generate the random string:

function GenerateRandomString($length = 5){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++){
    $randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}




Aucun commentaire:

Enregistrer un commentaire