dongtang5229 2014-05-14 02:15
浏览 60
已采纳

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 02: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部