首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PHP随机创建密钥

使用PHP随机创建密钥
EN

Stack Overflow用户
提问于 2015-05-24 13:36:35
回答 1查看 52关注 0票数 1

我有一个请求服务器密钥的移动应用程序,密钥结构包含7个字符,如下所示:

代码语言:javascript
复制
@ + [0-9] + [0-9] + [0-9] + [A-Z] + [A-Z] + [0-9] 

@876EU8, @668KI2 .......

虽然键最初有七个字符,在本例中是三个数字、两个字母和一个数字,但是通过计算,这个键最多可以得到676,000个键。

要使用此键,我将在PHP中使用以下代码:

代码语言:javascript
复制
function generateRandomString($length = 2) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$randomKeyNumber = rand(100,999);
$randomKeyLetter = generateRandomString();
$randomKeyLast = rand(0,9);

$randomKey = "#".$randomKeyNumber.$randomKeyLetter.$randomKeyLast;//Returns a key like @876TG9 

下一段代码检查数据库中是否存在密钥,如果存在,则随机选择另一个密钥,如果没有,则将密钥插入数据库并将该密钥返回给我的应用程序。

这段代码工作得很好,但是假设系统已经生成了总共65万个密钥,在这个代码中,它总是生成相同的键,而生成一个还不存在的密钥的可能性非常小。

我怎样才能解决这个问题,避免将来的问题?(按顺序创建密钥没有问题,如000AA0,000AA1,000AA2,000AA3 .999ZZ9)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-24 14:27:45

您可以做的是让一个PDO::query()发出一个SELECT COUNT(*)或简单地用您已经添加的所有键发出一个SELECT *语句,然后使用PDOStatement::fetchColumn()检索将要返回的行数(在本例中是全部)。

这是一个手动示例。

代码语言:javascript
复制
<?php
$sql = "SELECT COUNT(*) FROM Keys";
if ($res = $conn->query($sql)) {

    /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {

        /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT name FROM fruit WHERE calories > 100";
       foreach ($conn->query($sql) as $row) {
           print "Name: " .  $row['NAME'] . "\n";
         }
    }
    /* No rows matched -- do something else */
  else {
      print "No rows matched the query.";
    }
}

$res = null;
$conn = null;
?>

这是您需要的用于您的情况的代码:

代码语言:javascript
复制
<?php
$sql = "SELECT * From Keys";

if ($res = $conn->query($sql)) {

    /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {

        /* and then you get the id of the last one on the list, and to that one you add 1 */
         $last_id = $conn->lastInsertId();
         $new_id = $last_id + 1;
/* then you insert that in some place inside the key itself, that way you don't need to worry than two keys can be equal */
    }

  else {
      /* No rows matched, just create a key and add to the database here */
    }
}
¿>

或者,您可以将查询SELECT语句与PDO中的countRows结合使用,它在可移植应用程序和/或数据库中并不总是工作,但就好像我们不知道更多关于您的应用程序的信息一样,我们无法知道这是否有效。

PS。不要使用兰德()。使用兰德()代替。更有效地利用服务器的资源;)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30424120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档