DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

How I can create user activation token or url slugs?

Usually for user activation tokens I need good entropy in my randomness. Solutions based upon:

  • str_shuffle
  • shuffle
  • rand

Use time-based randomness therefore, any random slug for user activation can be predictable. On the other hand solutions based upon openssl_random_pseudo_bytes offer better randomness.

So, using the following pieces of code can be useful:

Example 1:

Just a random string:


// Set appropriate length

$length = 10;

$token = substr(base64_encode(openssl_random_pseudo_bytes(100)),0,$length);

Enter fullscreen mode Exit fullscreen mode

Example 2

Random alphanumeric string:

// Set appropriate length
$length = 10;

$pool = base64_encode(openssl_random_pseudo_bytes(100));

// If no need for numbers use '/[^a-zA-Z]/' instead
$pool = preg_replace('/[^a-zA-Z0-9]/',"",$pool);

$token = substr($pool,0,$length);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)