PHP Generating Random Strings And Numbers
How to create a random string of PHP. The code below for creating a unique ID number function.
PHP Function That Generating Random Strings
This PHP random_strings() function creates a combination of uppercase and lowercase letters, including underscore.
<?php
function random_strings($length = 10) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_';
$chars_length = strlen($chars);
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $chars[rand(0, $chars_length - 1)];
}
return $string;
}
//usage. set strings length
echo random_strings(15); //output d8iSfUi8484_rij
echo random_strings(5); //output j6yh2d
?>
PHP Random Number Function
This PHP random_numbers() function generates mixed numbers.
<?php
function random_numbers($length = 10) {
$numbers = '0123456789';
$numbers_length = strlen($numbers);
$number = '';
for ($i = 0; $i < $length; $i++) {
$number .= $numbers[rand(0, $numbers_length - 1)];
}
return $number;
}
//usage
echo random_numbers(15); //659854320686554
echo random_numbers(5); //12685
?>
Using PHP Get A Random Number Within Range
The rand() function generates a random integer. Example If you want a random integer between 1 and 10, use rand(1,10)
Generate random mixed string numbers and special characters with PHP
This PHP function generates random passwords or a mixed string of numbers and special characters.
<?php
function random_mixed($length = 8) {
$result = "";
$chars = "1234567890";
$chars .= "abcdefghijklmnopqrstuvwxyz";
$chars .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$chars .= "~!@#$%^&*()_+}{></[]|-,:;'\".?";
$chars_length = strlen($chars);
for ($i = 0; $i < $length; $i++) {
$result .= $chars[rand(0, $chars_length - 1)];
}
return $result;
}
// usage
echo random_mixed(10); // 4P0p*ByK!"
?>