An implementation of shortid in PHP

v1.1.0 2022-10-02 13:34 UTC

This package is auto-updated.

Last update: 2024-05-25 12:20:23 UTC


Total Downloads Build Status Code Climate Test Coverage codecov SensioLabsInsight License

This library is an implementation of ShortId for PHP.

Basic usage

Just call PUGX\Shortid\Shortid::generate() to get a random string with default length 7, like "MfiYIvI".

use PUGX\Shortid\Shortid;

require_once __DIR__.'/vendor/autoload.php';

$id = Shortid::generate();

Advanced usage

In the following example, you can see how to change the basic alphabet and default length.

Default alphabet uses all letters (lowercase and uppercase), all numbers, underscore, and hypen.

use PUGX\Shortid\Factory;
use PUGX\Shortid\Shortid;

require_once __DIR__.'/vendor/autoload.php';

$factory = new Factory();
// alphabet string must be 64 characters long
// length must be between 2 and 20 (default is 7)
// of course, a lower length is increasing clashing probability

$id = Shortid::generate();

As alternative, you can customize single generations:

use PUGX\Shortid\Shortid;

require_once __DIR__.'/vendor/autoload.php';

$id9 = Shortid::generate(9, 'é123456789àbcdefghìjklmnòpqrstùvwxyzABCDEFGHIJKLMNOPQRSTUVWX.!@|');
$id5 = Shortid::generate(5);

More readable strings

Sometimes, you want to avoid some ambiguous characters, like B/8 or I/l (uppercase/lowercase). In this case, you can pass a third parameter true to generate method. Notice that in this case the alphabet will be ignored, so it makes sense to pass a null one.


use PUGX\Shortid\Shortid;

require_once __DIR__.'/vendor/autoload.php';

$id = Shortid::generate(7, null, true);

Pre-defined values

If you need a deterministic string, instead of a random one, you can call directly the class constructor. This could be useful, for instance, when you need pre-defined data for testing purposes.

use PUGX\Shortid\Shortid;

require_once __DIR__.'/vendor/autoload.php';

$myFixedId = new Shortid('5h0r71d');
$anotherFixedId = new Shortid('fooBarZ');


If you want to use ShortId with Doctrine ORM, take a look to ShortId Doctrine type.

Doctrine and Symfony

If you want to use ShortId with Doctrine ORM and Symfony framework, take a look to ShortId Doctrine type bundle.

mbstring extension

This library uses a polyfill, so it can used in environments where mbstring native extension is not available.

If, instead, your environment is offering such extension, you can avoid installing polyfill by configuring replace entry in your composer.json.