How to userandom_bytes() function. (Cryptographically Secure) in PHP

The random_bytes() function generates cryptographically secure pseudo-random bytes, which can later be converted to hexadecimal format using bin2hex() function. 

Example : 

php
<?php
$n = 20;
$result = bin2hex(random_bytes($n));
echo $result;
?>

Output
67de19022831ea109df3ab3b483a2c0912005fdc

Generating Random String Using PHP

Generate a random, unique, alpha-numeric string using PHP. Examples:

EA070
aBX32gTf

Table of Content

  • Brute Force
  • Using Hashing Functions 
  • Using uniqid() function
  • Using random_bytes() function. (Cryptographically Secure) 
  • Using random_int() in a Custom Function

Similar Reads

Approach 1: Brute Force

The first approach is the simplest one to understand and thus brute force....

Approach 2: Using Hashing Functions

PHP has a few functions like md5(), sha1() and hash(), that can be used to hash a string based on certain algorithms like “sha1”, “sha256”, “md5” etc. All these function takes a string as an argument and output an Alpha-Numeric hashed string....

Approach 3: Using uniqid() function

The uniqid( ) function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). By default, it returns a 13 character long unique string....

Approach 4: Using random_bytes() function. (Cryptographically Secure)

The random_bytes() function generates cryptographically secure pseudo-random bytes, which can later be converted to hexadecimal format using bin2hex() function....

Approach 5: Using random_int() in a Custom Function

Using random_int() in a custom function generates a secure random string by selecting characters from a predefined set. It iterates to build a string of specified length, ensuring cryptographic security. Suitable for sensitive applications like tokens or passwords....