Random String

Just some functions for generating random strings in PHP.

function randstr($len=8, $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
    $i = 0;
    $str = '';
    $randmax = strlen($chars)-1;

    for($i=0; $i<$len; ++$i) {
        $str .= $chars[mt_rand(0,$randmax)];
    }

    return $str;
}

function randkey($len=32) {
    return randstr($len, '`1234567890-=qwertyuiop[]\\asdfghjkl;\'zxcvbnm,./ ~!@#$%^&*()_+{}|:"<>?');
}

randkey is good for generating salt strings and such, randstr is good for stuff like short URLs. Of course, you can pass in whatever characters you want.

Posted in

Leave a comment

Leave a Reply

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