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 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)