Nick Nick - 2 months ago 7
PHP Question

Generating a random value, and inserting to the db in php

Alright so I am trying to generate a random value, using random_bytes, tell the user his unique ID, and then insert to the database.

I'm using isset so I tried doing $id = bin2hex(random_bytes(16)) but it generates another ID when the user clicks the Register button, meaning the value he saved is not the one that was inserted to the database.

Basically, a random identifier that is generated for him and he needs to save in order to log in (serves as the username).

Thanks!

I know it's something to do with the isset because the value is generated AFTER the user posts the form but I want to tell him something that was not yet generated. not sure how to do it.

<?php

if (isset($_POST['regbutton'])) {

$username = bin2hex(random_bytes(16));
$password = ($_POST['password']);
$repeatpw = ($_POST['repeatpw']);

// blah blah validations
// executes a database query and insets the $username variable into the db

HTML - <input type="text" class="form-control" name="username" value="<?php echo $username; ?>">

Answer
<?php
session_start();

// generate a random "username" if you haven't done so yet
if (!isset($_SESSION['username'])) {
  $_SESSION['username'] = bin2hex(random_bytes(16));
}
$username = $_SESSION['username'];

// check for form post
if (isset($_POST['regbutton'])) {   

  // get values from form post
  $username = $_POST['username'];
  $password = $_POST['password'];
  $repeatpw = $_POST['repeatpw'];

  // blah blah validations
  if ($username != $_SESSION['username']) {
    // user changed the username you showed him
  }
  // blah blah other validations
  // executes a database query and insets the $username variable into the db
}