How to generate simple random password from a given string using PHP ? (original) (raw)
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 `
strlength=strlen(str_length = strlen(strlength=strlen(str); // Check if the $len is not provided // or lenisgreaterthanlen is greater than lenisgreaterthanstr_length // then assign strlengthtostr_length to strlengthtolen if($len == 0 || len>len > len>str_length){ len=len = len=str_length; } // Iterate $len times so that the // resulting string's length is // equal to $len for($i = 0; i<i < i<len; $i++){ // Concatenate random character // from strwithstr with strwithpass pass.=pass .= pass.=str[rand(0, $str_length)]; } return $pass; } // Print password of length 5 from // the given string $str = "GeeksForGeeks"; echo get_password($str, 5) . "\n"; // Print password of length 15 from // the given string $str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"; echo get_password($str, 15) ."\n
"; // Print password if the length // is not given echo get_password($str) . "\n
"; ?>
`
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 `
strlength=strlen(str_length = strlen(strlength=strlen(str); // Check if the $len is not provided // or lenisgreaterthanlen is greater than lenisgreaterthanstr_length // then assign strlengthintostr_length into strlengthintolen if($len == 0 || len>len > len>str_length){ len=len = len=str_length; } // Shuffle the string pass=strshuffle(pass = str_shuffle(pass=strshuffle(str); // Extract the part of string pass=substr(pass = substr(pass=substr(pass, 0, $len); return $pass; } // Print password of length 5 from // the given string $str = "GeeksForGeeks"; echo get_password($str) . "\n"; // Print password of length 15 from // the given string $str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"; echo get_password($str, 15) ."\n
"; // Print password if the length is // not given echo get_password($str) . "\n
"; ?>
`
Output:
oeFssGkeGrkee rxIhAjCi47wgW1z r4LZQqlOFGU36i7gEAtzwsnduNXhHKD92ajpxBJc1MRvVmbyeokPIWfCTSY85