PHP code to generate a random set of characters

The code below is a modified version of a random string generator that generates a random string of a given (user input) length.

Characters are picked from within a seed variable containing all the available characters to choose from.

Code:

<?php
// PHP function to print a  
// random string of length n 
function getRandomString($n) 
{ 
    // Final Output
    $outputString = ""; 

    // Charecters to choose from
    $seedString = "@#$%^&*()_abcdfghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 

    $len = strlen($seedString); 

    // Loop to create random string 
    for ($i = 0; $i < $n; $i++) 
    { 
        // Generate a random index to pick  
        // characters 
        $index = rand(0, $len - 1); 

        // Concatenating the character  
        // in resultant string 
        $outputString = $outputString . $seedString[$index]; 
    } 

    // Return the random generated string 
    return $outputString; 
} 

// Unit Test

//Requested String Size
$n = 5; 
echo getRandomString($n); 
 
?>

About the Author: admin

Leave a Reply

Your email address will not be published. Required fields are marked *