• Skip to primary navigation
  • Skip to main content
  • Skip to footer
  • Home
  • Blog
  • Search

Kevin Dees

Full-Stack PHP Development

  • Twitter
  • Github
  • LinkedIn
You are here: Home / PHP / PHP UUID without a Library

PHP UUID without a Library

April 23, 2020 by Kevin Leave a Comment

red ladybug on white surface

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.

Filed Under: PHP, Tips, Web

Reader Interactions

Leave a Reply Cancel 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.

Footer

Get Dare To Code

Get the latest on full-stack PHP development in your inbox with a bi-weekly lesson from Kevin Dees.

Copyright © 2021 · Kevin Dees · Log in