Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kenprogrammer's avatar

PHP How to Generate Unique codes?

I've been using the using the following code snippet for sometime to generate unique numbers e.g customer no.s etc.

		/*
         * Generate unique random string
         *
         * @return string
         */
        public function generaterandomString($length) {

            $chars = "abcdefghijkmnopqrstuvwxyz023456789";

            srand((double)microtime()*1000000);

            $i = 0;

            $randStr = '' ;

            while ($i <= $length) {

                $num = rand() % 33;

                $tmp = substr($chars, $num, 1);

                $randStr = $randStr . $tmp;

                $i++;

            }

            return $randStr;
        }

I later realized that duplication occurs when dealing with a lot of records.

How can generate unique codes? Modification of the above snippet or suggestion of a new approach will be highly appreciated.

0 likes
9 replies
kenprogrammer's avatar

@Sinnbeck Yes for account verification codes I generate 6 letters for payment references 8 to 10

I read somewhere on Laravel documentation that there are chances of uuid generate a duplicate

kenprogrammer's avatar

@Sinnbeck I use the function for both Laravel and Vanilla PHP. There are times I wanted to use UUID the i came across that info

kenprogrammer's avatar

@Sinnbeck This quiz in not related though. If you don't mind, what makes the storage folder to loose permission after seeding or migration? I've a multitenancy app where by after account creation and activation. I've commands to create database, migrate and seed database. The commands are executed by Laravel Task scheduler. Once the tenant is provisioned, they can login but cannot open dashboard. The error is Permission denied. After I chmod -R 777 storage manually the dashboard is accessible. Next time after another tenant is provisioned same error.

Please or to participate in this conversation.