Search the blog

When generating a token for things like authentication it is important you do not use functions like rand(), uniqid() and mt_rand() since they are not cryptographically secure.

This function below allows you to generate cryptographically secure tokens to a given length in bits, bytes or characters.

function generateSecureToken($length, $lengthType) {

    // Work out byte length
    switch($lengthType) {

        case 'bits':
            $byteLength = ceil($length / 8);

        case 'bytes':
            $byteLength = $length;

        case 'chars':
            $byteLength = $length / 2; // In hex one char = 4 bits, i.e. 2 chars per byte

            return false;


    // Try getting a cryptographically secure token
    $token = openssl_random_pseudo_bytes($byteLength);

    if ($token !== false) {

        return bin2hex($token);

    else {

        // openssl_random_pseudo_bytes failed
        return false;



var_dump(generateSecureToken(128, 'bits'));          // string(32) "19e25e5adc713560728587beab0208c6" (128-bit)
var_dump(generateSecureToken(16,  'bytes'));         // string(32) "a5b60494f76f9cd5587cdd7a8ef26de7" (16 bytes)
var_dump(generateSecureToken(16,  'chars'));         // string(16) "5136faabb5c7d144" (16 characters)
var_dump(generateSecureToken(128, 'invalid type'));  // bool(false) 
Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.