Categories
PHP Tips Web

PHP UUID without a Library

A little bit of PHP is sometimes all you need to solve a problem. In our case, we need just a little PHP code to generate a UUID.

/**
 * Binary to Hex UUID
 *
 * @param int $half Half the length of the string to return.
 *
 * @return string
 * @throws Exception
 */
function uuid(int $half = 16)
{
    return bin2hex(random_bytes($half));
}

/**
 * UUID v4
 *
 * Formatted as follows 7544eee6-4ac1-5883-21a6-0759de6e6873
 *
 * @return string
 * @throws Exception
 */
function uuid4()
{
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(uuid(16), 4));
}

When you need more I recommend using Ben Ramsey‘s PHP UUID package.

P.S. When using a UUID in the database I’d still run a unique check for good measure.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.