Community Post

Generating random keys with Keygen

Glad Chinda
💬 comments

Most times, building your PHP applications demands that you generate random strings, numbers or even bytes, such as: user IDs, api keys, verification tokens, etc. The Keygen package is a PHP package that makes generating random keys a breeze. The package generates random character sequences called keys.

Installing Keygen

In order to start using the Keygen package, you need to install it as a dependency for your project. The Keygen package is available at the Packagist repository and can easily be installed as a dependency for your project using Composer. To install, you run the composer tool in the root folder of your project.

composer require gladcodes/keygen

This will install the Keygen package from Packagist and create/modify a vendors folder and a composer.json file in the root of your project. That's all you need to install the Keygen package and get going.

Table of Contents

    Generating Numeric Keys

    Numeric keys are commonly used as IDs. They are generated by statically calling the numeric() method of the Keygen\Keygen class. It takes an optional length argument which specifies the length of the numeric key and defaults to 16 if omitted or not a valid integer.

    require __DIR__ . '/vendor/autoload.php';
    use Keygen\Keygen;
    $id_12 = Keygen::numeric(12)->generate();
    $id_16 = Keygen::numeric()->generate();
    echo $id_12; // 011683218639
    echo $id_16; // 9352941287643963

    Usually it is not desirable to have zeroes starting-off numeric keys. A slight variation can be made to the generation code to ensure there are no zeroes at the beginning of the numeric keys. The following code snippet creates a custom function to wrap the generation mechanism.

    require __DIR__ . '/vendor/autoload.php';
    use Keygen\Keygen;
    function generateID($length = null) {
        // ensures the length is an integer
        $length = is_int($length) ? $length : null;
        // prefixes the key with a random integer between 1 - 9 (inclusive)
        return Keygen::numeric($length - 1)->prefix(mt_rand(1, 9))->generate(true);
    $id_12 = generateID(12);
    $id_16 = generateID();
    echo $id_12; // 473840499215
    echo $id_16; // 2684603281019122

    The snippet above uses the prefix() method to add a non-zero integer at the beginning of the numeric key. This is known as an affix. The Keygen package also provides a suffix() method for adding characters at the end of generated keys. For more details about the features of the Keygen package such as: Key Affixes and Key Transformations, see the README document of the Keygen package.

    Generating Alphanumeric Keys and Tokens

    An alphanumeric key is a random sequence of characters containing a combination of uppercase alphabets, lowercase alphabets and digits. It can be generated by statically calling the alphanum() method of the Keygen\Keygen class in much the same way as the numeric() method.

    A token is a random base64 encoded string. It is commonly used as app secrets and api keys. It can be generated by the token() method of the Keygen\Keygen class.

    require __DIR__ . '/vendor/autoload.php';
    use Keygen\Keygen;
    $alnum = Keygen::alphanum(15)->generate();
    $token = Keygen::token(28)->generate();
    echo $alnum; // TFd5X74Pr9ZOiG2
    echo $token; // 4HE1xQz+4ks0Td128KSO/kBivd79

    Generating Random Bytes

    The Keygen package also generates random bytes by calling the bytes() method of the Keygen\Keygen class. Random bytes may not be very useful for your application, hence, the Keygen package provides the hex() method to return the random bytes as hexadecimal.

    require __DIR__ . '/vendor/autoload.php';
    use Keygen\Keygen;
    $bytes = Keygen::bytes(20)->generate();
    $hex = Keygen::bytes(20)->hex()->generate();
    echo $bytes; // 
    echo $hex; // 9f802a80aaf4b5e89e14

    A Brief on Key Transformations

    The Keygen package allows for one or more transformations to be applied on keys before they are generated. A transformation is simply a callable that can take the generated key as the first argument and returns a string. Each transformation is executed on the generated key in the same order they are specified before the key is returned.

    require __DIR__ . '/vendor/autoload.php';
    use Keygen\Keygen;
    $reference = Keygen::numeric(20)->generate(function($key) {
        return join('-', str_split($key, 4));
    $filename = Keygen::bytes()->suffix('.png')->generate(true, ['strrev', function($key) {
        return substr(md5($key), mt_rand(0,8), 20);
    }], 'strtoupper');
    echo $reference; // 2129-1489-0676-5152-9337
    echo $filename; // 159D702E346F74E3F0B6.png

    Advanced Usage

    For a more detailed documentation and advanced usage of the Keygen package, see the README document of the Keygen package.

    Glad Chinda

    7 posts

    Full-stack web developer learning new hacks one day at a time. Web technology enthusiast. Enjoys playing with React, JavaScript(NodeJS) and PHP.