How To Generate Random Unique Token in PHP Tutorial

Reading Time: 4 minutes
2,334 Views

Inside this article we will see the concept i.e How To Generate Random Unique Token in PHP. Article contains the classified information about generating a unique random alphanumeric token value in PHP. Tutorial is super easy to understand and implement it in your code as well.

If you are looking for a solution to get a random unique string value of 32 chars, 16 chars, 10 chars, etc then this article will help you a lot for this.

In PHP we have several pre-built functions available which we can use in php development. So, here we will use some kind of functions to work around generating a unique random token value in PHP.

Learn More –

Let’s get started.

Example #1: Generate Unique Token Value

Create index.php file in your localhost path. Open file and write this code into it.

<?php

// Generate a random string.
$token = openssl_random_pseudo_bytes(16);

// Convert the binary data into hexadecimal representation.
$token = bin2hex($token);

// 32 characters long token value
echo $token;

Concept

Here, we have used two PHP functions: openssl_random_pseudo_bytes() & bin2hex(). These two functions will work and generate 32 characters long alphanumeric token value if we pass bytes value equals to 16.

Output

d90eeb05de70c68ab2115c372dee9197

Whenever you refresh your application, you will get a new token value.

Token value with 32 characters

$token = openssl_random_pseudo_bytes(16);

Token value with 16 characters

$token = openssl_random_pseudo_bytes(8);

Token value with 10 characters

$token = openssl_random_pseudo_bytes(5);

Example #2: Generate Unique Token Value

Create index.php file in your localhost path. Open file and write this code into it.

<?php

// Generate a random string & Convert the binary data into hexadecimal representation.
$token = bin2hex(random_bytes(16));

// 32 characters long token value
echo $token;

Concept

Here, we have used two PHP functions: bin2hex() & random_bytes(). These two functions will work and generate 32 characters long alphanumeric token value if we pass bytes value equals to 16.

Output

bac82b76456c8355e3ebbd0b9d17d833

We hope this article helped you to learn How To Generate Random Unique Token in PHP Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.