Random string

<?php
 
/**
 * Generates a random string.
 *
 * @param    int    $length
 *   The length of the string
 * @param    string $ranges
 *   The characters to use, formatted like a regex character class (a-fA-F0-9)
 * @param    bool   $unique
 *   Every character in the result is unique or not
 * @return   string
 *   The resulting string.
 */
require_once('preg_expand.php');
function random_string($length = 6, $ranges = 'a-zA-Z0-9', $unique = false) {
    $out = '';
    $chars = preg_expand($ranges, 0);
    if ($unique) {
        $keys = array_rand($chars, $length);
    } else {
        for ($i = $length; $i--;) {
            $keys[] = array_rand($chars);
        }
    }
    foreach ($keys as $k) {
        $out .= $chars[$k];
    }
    return $out;
}
 
/**
 * Quick and simple version
 */
function random_string_simple($length = 6) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    for ($i = $length, $out = ''; $i--;) {
        $out .= $chars{rand(0, 61)};
    }
    return $out;
}
 
?>

Example

<?php
 
echo '<h4>Default:</h4>', random_string(), '<br /><br />';
 
echo '<h4>8 characters, A-F0-9:</h4>', random_string(8, 'A-F0-9'), '<br /><br />';
 
echo '<h4>6 characters, a-z, unique:</h4>', random_string(6, 'a-z', 1), '<br /><br />';
 
echo '<h4>Simple:</h4>', random_string_simple();
 
?>

Output

Default:

shAjlw

8 characters, A-F0-9:

9A181CE7

6 characters, a-z, unique:

fgkqsw

Simple:

RsxWZj

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.