dongtang5229 2014-05-14 10:15
浏览 59
已采纳

PHP中独特的6位十六进制代码生成器

I am working on a PHP project and i would like to generate an id that is unique and user friendly like the black berry messenger user pin.

It would best prefer if it was six characters long

Is there any algorithm or a combination of PHP functions i can use? if not what is my best bet? Am a newbie.

  • 写回答

5条回答 默认 最新

  • dongre6227 2014-05-14 10:23
    关注

    Lowercase:

    sprintf('%06x', mt_rand(0, 16777215))
    

    Uppercase:

    sprintf('%06X', mt_rand(0, 16777215))
    

    (demo)

    Reference:

    16777215 is 166-1. It's likely that you'll get dupes so you need to store previous values somewhere (typically a database) and check for uniqueness.

    Another solution is to generate all 17 million codes at once, shuffle them and pick one each time.

    First time:

    $all_codes = range(0, 16777215);
    shuffle($all_codes);
    
    $sql = 'INSERT INTO all_codes (id, code, taken) VALUES (?, ?, ?)';
    foreach ($all_codes as $index => $code) {
        $values = [
            $index+1,
            sprintf('%06X', $code),
            false
        ];
        $your_database_library->query($sql, $values);
    }
    

    This script is pure non-optimised brute force so you'll need to increase PHP memory limit (it needs like half GB) but it's a one-time task.

    Then, every time you need a code (let's assume MySQL):

    SELECT id, code
    FROM all_codes
    WHERE used = 0
    ORDER BY 1
    LIMIT 1
    FOR UPDATE;
    
    UPDATE all_codes
    SET used = 1
    WHERE id = ?;
    

    Alternatively, you could store them in sequence and pick randomly among the unused, making sure to implement a solution that's fast in your DBMS (because you're randomising every time) but that looks like more work :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题