How To Generate a Random Token In PHP

In this post we will see how to generate random secure token in PHP.

We can give security in different module of web application with use of these random generated token. In which case and why we use it?.

This is used to protect webpage against unwanted action .In many more cases you can use it for security purpose in web application.

Let’s talk about the cases when you should prefer to use it.

How To Generate a Random Token In PHP

Why token is used?

  • The one of the most reason is to protect web application against Cross-Site Request Forgery (CSRF) attack. Now we have new term what is CSRF? It is type of attack on web application for perform unusual and unwanted behaviour on trusted site.
  • To verify email address of user during signup process.
  • In login authentication to give limited resources with session of limited duration. This helps to restrict user to get limited resource access. In this way you can secure web application resources.
  • In forgot password request mail send.

User gets email with link having random token. When user click on link to verify email id then check for token exist  in email link matches with generated for user is same or not. If match both then user is valid.

How to Generate Token?

With writing few line of script, cryptographically secured tokens generate in PHP. To generate it we use some inbuilt PHP functions.

<?php
//generate random string
$rand_token = openssl_random_pseudo_bytes(16);
//change binary to hexadecimal
$token = bin2hex($rand_token);
//token generated
echo $token;
?>

openssl_random_pseudo_bytes()  function generate cryptographically secure source of pseudorandom bytes. In this simple snippet you can generate secure random tokens in PHP.

With use of above snippet give security little bit more to your web application. That’s all.

Leave a Comment