How to userandom_int() in a Custom Function in PHP
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.
Example:
<?php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[random_int(0, $charactersLength - 1)];
}
return $randomString;
}
// Generate a random string of length 10
$randomString = generateRandomString(10);
fwrite(STDOUT, $randomString . PHP_EOL);
?>
Output
FQRp5bDjsw
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
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