How to generate simple random password from a given string using PHP ?
Last Updated :
21 May, 2021
In this article, we will see how to generate a random password using the given string. We have given a string and the task is to generate a random password from it.
Example:
Input: abgADKL123
Output: abgADKL123
Input: geeksforgeeks
Output: egksegsfroeke
To achieve this, we use the following approaches.
Approach 1: In this approach, we use the PHP rand() function and create a temporary variable, and using for loop we create random characters from the given string and concatenate that character to the temporary variable. Following is the implementation of this approach.
PHP code:
PHP
<?php
function get_password( $str , $len = 0) {
$pass = "" ;
$str_length = strlen ( $str );
if ( $len == 0 || $len > $str_length ){
$len = $str_length ;
}
for ( $i = 0; $i < $len ; $i ++){
$pass .= $str [rand(0, $str_length )];
}
return $pass ;
}
$str = "GeeksForGeeks" ;
echo get_password( $str , 5) . "\n<br/>" ;
$str =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789" ;
echo get_password( $str , 15) . "\n<br/>" ;
echo get_password( $str ) . "\n<br/>" ;
?>
|
Output:
skGse
iWwf9jWZZE9ZL7O
GhRQ8zK4wpX93srUj1LhjsBEeBwBwo4Bh43RyZeSFZbwjVoonkKBgfXiBrEpY
Approach 2: In this approach, we use the PHP str_shuffle() function, and then we use the substr() function to extract the part of the given string.
PHP code:
PHP
<?php
function get_password( $str , $len = 0) {
$pass = "" ;
$str_length = strlen ( $str );
if ( $len == 0 || $len > $str_length ){
$len = $str_length ;
}
$pass = str_shuffle ( $str );
$pass = substr ( $pass , 0, $len );
return $pass ;
}
$str = "GeeksForGeeks" ;
echo get_password( $str ) . "\n<br/>" ;
$str =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789" ;
echo get_password( $str , 15) . "\n<br/>" ;
echo get_password( $str ) . "\n<br/>" ;
?>
|
Output:
oeFssGkeGrkee
rxIhAjCi47wgW1z
r4LZQqlOFGU36i7gEAtzwsnduNXhHKD92ajpxBJc1MRvVmbyeokPIWfCTSY85