Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

PHP UNIQUE ID's / UUID

Posted on 2010-01-07
4
Medium Priority
?
668 Views
Last Modified: 2013-12-12
What's the best way to generate a UUID in PHP? Should it be pseudo random? or time based?

The ID's will be used with mysql as a primary key. There will be a lot of inserts/updates on the table, as well as joins.

The ID will also be used as a temporary session ID (e.g. passed in the URL), so auto increment would not be suitable.
0
Comment
Question by:jwzk
  • 2
4 Comments
 
LVL 27

Expert Comment

by:Cornelia Yoder
ID: 26201561
I recently answered this question for someone else, you can see the answer here:

http://www.experts-exchange.com/Database/MySQL/Q_25016779.html
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 26201654
Run this and look for a unique ID - many PHP installation populate it.

<?php phpinfo(); ?>

You can use md5(rand()) to get something that is nearly sure to be random and unique.  If you want a shorter string (md5 produces 32 chars - a lot if you have to read it over the phone) and a guarantee that it is unique, you can use this sort of algorithm.

HTH, ~Ray
<?php // RAY_UNIQUE.php

// THIS IS A TEACHING EXAMPLE, NOT COMPLETE CODE.
//
// THE RANDOM NUMBER COULD BE A RANDOM ALPHA-NUMERIC STRING, TOO
// THE LENGTH OF THE RESULTING STRING AND THE NUMBER OF CHARACTERS IN THE INPUT STRING
// GREATLY AFFECT THE NUMBER OF POSSIBLE UNIQUE COMBINATIONS.
//
// IF YOU USE LETTERS AS WELL AS NUMBERS, YOU WANT TO OMIT THE LETTERS THAT LOOK
// LIKE NUMBERS, SO REMOVE THE UPPER-CASE O AND THE LOWER-CASE L, ETC.
//
// YOU MIGHT WANT TO REMOVE THE VOWELS, AS WELL, IF YOU WANT TO REDUCE THE RISK OF
// GENERATING A NATURAL LANGUAGE WORD.
//
// THE SEED ALPHABET IS IN THE VAR '$chr'




// A FUNCTION TO CREATE A RANDOM 12-DIGIT NUMBER
function random_numeric_string($length=12)
{
// POSSIBLE COMBINATIONS = pow($length,strlen($chr)); = 1.2E+11 IF LENGTH IS 12
//            1...5...10...15...20...
    $chr = "0123456789";
    $str = "";

    // ADD RANDOM CHARACTERS TO THE STRING UNTIL IT IS OF THE CORRECT LENGTH
    while(strlen($str) < $length)
    {
        $str .= substr($chr, mt_rand(0,(strlen($chr))), 1);
    }
return $str;
}




// A FUNCTION TO ENSURE THAT THE RANDOM NUMBER IS UNIQUE
function make_new_coupon_code()
{
    $code = '';
    while ($code == '')
    {
        // GENERATE A UNIQUE AND RANDOM TOKEN
        $code = random_numeric_string();

        // ATTEMPT TO INSERT THE CODE STRING
        $isql = "INSERT INTO coupons ( code ) VALUES ( '$code' )";

        // IF THE INSERT QUERY FAILS
        if (!$i = mysql_query($isql))
        {
            // GET THE ERROR NUMBER FROM MYSQL
            $err = mysql_errno();

            // DUPLICATE - DISCARD THIS CODE AND TRY AGAIN
            if ($err == 1062)
            {
                $code = '';
            }
            // SOMETHING ELSE, BUT NOT DUPLICATE UNIQUE FIELD
            else
            {
                /* HANDLE FATAL QUERY ERROR */
            }
        } // END INSERT
    } // END WHILE
    return $code;
}




// CALLING SEQUENCE:
$my_unique_string = make_new_coupon_code();




// THE DATA BASE COLUMN DEFINITION
code VARCHAR(12) UNIQUE NOT NULL

Open in new window

0
 

Author Comment

by:jwzk
ID: 26201823
Would you say this type of ID would be better suited than say an actual UUID? Also, performance wise, this database will end up with 20m+ rows.
0
 
LVL 27

Expert Comment

by:Cornelia Yoder
ID: 26202807
My solution generates numbers, so you can make the numbers as large as you want (within the constraints of MySQL), and numbers tend to be easier to work with.  If this will be a primary key, it will be much easier to deal with than a string of letters and hyphens.

I don't know for sure, but I suspect indexing (as is always done for keys) will be quicker using integers than for complex strings.

Just make the maximum number about 5 orders of magnitude larger than the number of them that you expect to use.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This post looks at MongoDB and MySQL, and covers high-level MongoDB strengths, weaknesses, features, and uses from the perspective of an SQL user.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question