Brute Force
The first approach is the simplest one to understand and thus brute force.
It can be achieved as follows:
- Store all the possible letters into a string.
- Generate random index from 0 to string length-1.
- Print the letter at that index.
- Perform this step n times (where n is the length of string required).
Example :
<?php
$n=10;
function getName($n) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $n; $i++) {
$index = rand(0, strlen($characters) - 1);
$randomString .= $characters[$index];
}
return $randomString;
}
echo getName($n);
?>
Output
6aruSzs0qJ
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
Contact Us