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.


Comments

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.

Get Involved & Explore More

an abstract painting with blue and yellow colors

Catch up on what I’ve been writing lately.

Show your gratitude.

Join Dare To Code Email List

Get emails from me on full-stack PHP development by subscribing to the Dare To Code mailing list.