How to generate fixed length random string A-Z, 0-9 in PHP ?

Generate fixed length random string A-Z, 0-9:-

function generateRandString($length = 10) {
    $charactersData = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($charactersData);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $charactersData[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
generateRandomString()

Generate fixed length random string A-Z  ( Capital Letters ):-

function generateRandString($length = 10) {
    $charactersData = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($charactersData);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $charactersData[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
generateRandomString()

Fixed length random number 0-9:-

function generateRandString($length = 10) {
    $charactersData = '0123456789';
    $charactersLength = strlen($charactersData);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $charactersData[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
generateRandomString()

Fixed length random string A-Z, 0-9 and Symbol:-

function generateRandString($length = 10) {
    $charactersData = '[email protected]#$%^&*()_+=?><';
    $charactersLength = strlen($charactersData);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $charactersData[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
generateRandomString()

 

How to create Random String in Codeigniter:-

echo random_string('alnum', 16);

echo random_string('alpha', 16);
  • Using alnum parameter you create random Alpha-numeric string with lower and uppercase characters.
  • Using alpha parameter you create random lower and uppercase letters only
  • The last parameter is Output string length in (int)

“random_string” is a Codeigniter default function to create a fixed length random string and number.