2016-09-30 114 views
-2

好了,所以我想生成一个随机值,使用random_bytes,告诉用户他的唯一的ID,然后插入到数据库中。生成一个随机值,并插入到数据库中的PHP

我使用isset,所以我尝试做$ id = bin2hex(random_bytes(16)),但当用户单击注册按钮时它会生成另一个ID,这意味着他保存的值不是插入到数据库。

基本上,这对他来说是生成和他需要以登录(作为用户名),以节省一个随机标识符。

谢谢!

我知道这件事情做的isset,因为值用户的帖子后生成的形式,但我想告诉他不要在还没有产生的东西。不知道该怎么做。

<?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; ?>"> 
+0

为什么一定是随机的?顺序有问题吗? –

+0

请向我们展示您的代码。如果我们不知道你在做什么,我们就无能为力。 – Chris

+0

我不太喜欢用户知道有多少人的想法。 – Nick

回答

1
<?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 
} 
+0

非常感谢马克,这实际上工作!但是有没有办法插入原始的生成值,即使用户改变它的客户端? (而不是杀死表格并且告诉他他改变了它)。 – Nick

+0

不要从表单中读回用户名;消除$ username = $ _POST ['username']和if(...)检查它。 $用户名仍然是从$ _SESSION ['用户名']拉出的值。 –

+0

是的,我意识到这样做的安全问题。多谢一个人,拯救了我的一天。 – Nick

0

如果使用智威汤逊,您可以生成令牌,检查出the JWT library