Andurit
Andurit

Reputation: 5762

Always create UNIQUE ID without using database - PHP

I have I have static HTML / JS page without any database (I don't need it). However I start fight with some issue. I need to generate random ID which have to be unique(used once and never ever again).

Stardard MySQL way:

On standard application I will do it with storing all used IDs in database and when needed new one I will simply

// I generate ID here, let's say it's 123
SELECT COUNT(id) FROM table WHERE id = 123

My solution which may be not the best one:

I am thinking alternative may be some storing in file

// Let's generate ID here, and make it 123 again

    $handle = fopen("listOfIDs.txt", "r");
    if ($handle) {
        $used = false;
        while (($line = fgets($handle)) !== false) {
            if($line = 123) {
              $used = true;
              break;
          }
        }        
        fclose($handle);
        return $used;
    } else {
        // error opening the file.
    } 

Dispite the fact I can imagine my option may work it could be super slow when file become bigger.

Question:

What's the best way to keep simple unique IDs without using database.

Edit: I forgot to mentioned that unique ID have to be numbers only.

Upvotes: 1

Views: 1466

Answers (3)

Edson Horacio Junior
Edson Horacio Junior

Reputation: 3143

You can use PHP uniqid with $more_entropy = true, which increases the likelihood that the result will be unique.

$id = uniqid("", true);

You can also work some random number out using current date and time, etc. You should consider how fast the users may generate these numbers, if it's super fast, there might be a possibility of two different users generating the same $id because it happened at the same time.

Upvotes: 0

Felippe Duarte
Felippe Duarte

Reputation: 15131

You could use uniqid(), str_rand(something), timestamp, some hash with random data that you probably never get twice.

Or, doing your way, you could have a single line with information in this file, just the last used id:

$fp = fopen("lastID.txt", "r+");

if (flock($fp, LOCK_EX)) {  // lock the file
    $lastId = fgets($fp);   // get last id
    $newId = $lastId +1;    //update the id
    ftruncate($fp, 0);      // truncate file
    fwrite($fp, $newId);    //write the new Id
    fflush($fp);            // flush output
    flock($fp, LOCK_UN);    // release the lock
} else {
    throw new Exception("Could not get the lock");
}

fclose($fp);

return $newId;

Upvotes: 1

Daniel Valls Estella
Daniel Valls Estella

Reputation: 93

Maybe you can use a mix of the current timestamp, the request ip, and a randomnumber:

$unique = microtime().$_SERVER['REMOTE_HOST'].rand(0,9999);

Sure theorically you can get a request that executes this operation in the same microtime, with the same remote host, and matching the random number, but it's almost impossible, I think.

Upvotes: 0

Related Questions