PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

后端 未结 28 2673
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 22:20

How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends y

28条回答
  •  萌比男神i
    2020-11-21 23:02

    When trying to generate a random password you are trying to :

    • First generate a cryptographically secure set of random bytes

    • Second is turning those random bytes into a printable string

    Now, there are multiple way to generate random bytes in php like :

    $length = 32;
    
    //PHP 7+
    $bytes= random_bytes($length);
    
    //PHP < 7
    $bytes= openssl_random_pseudo_bytes($length);
    

    Then you want to turn these random bytes into a printable string :

    You can use bin2hex :

    $string = bin2hex($bytes);
    

    or base64_encode :

    $string = base64_encode($bytes);
    

    However, note that you do not control the length of the string if you use base64. You can use bin2hex to do that, using 32 bytes will turn into a 64 char string. But it will only work like so in an EVEN string.

    So basically you can just do :

    $length = 32;
    
    if(PHP_VERSION>=7){
        $bytes= random_bytes($length);
    }else{
        $bytes= openssl_random_pseudo_bytes($length);
    } 
    
    $string = bin2hex($bytes);
    

提交回复
热议问题