uniqid

(PHP 3, PHP 4, PHP 5)

uniqid -- Generate a unique ID

Description

string uniqid ( [string prefix [, bool more_entropy]] )

uniqid() returns a prefixed unique identifier based on the current time in microseconds. prefix is optional but can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. Up until PHP 4.3.1, prefix could only be a maximum of 114 characters long.

If the optional more_entropy parameter is TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which should make the results more unique.

With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.

注: The prefix parameter became optional in PHP 5.

If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along these lines:

<?php
// no prefix
$token = md5(uniqid());

// better, difficult to guess
$better_token = md5(uniqid(rand(), true));
?>

This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.


add a note add a note User Contributed Notes
mimec
25-Aug-2006 04:36
Here is the correct version of a function generating a pseudo-random UUID according to RFC 4122:

<?php

function uuid()
{
   return
sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
      
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
      
mt_rand( 0, 0x0fff ) | 0x4000,
      
mt_rand( 0, 0x3fff ) | 0x8000,
      
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );
}

?>

The version and variant is located at the MSB (most significant bits) of the time_hi_and_version and clock_seq_hi_and_reserved fields, not the LSB as in dholmes version.
admin at code-dynasty dot net
09-Jul-2006 11:46
I'm not too fond of the recommendation to use an MD5 of the unique ID for session IDs. It would be a better idea just to use uniqueid(rand(), true) without the MD5, because even though it's a rare circumstance, MD5 is a hash, not an encryption, which means it has collisions. Therefore you theoretically could have multiple users given the same session ID which could result in one user's ability to access another user's data.
dholmes at cfdsoftware dot net
09-May-2006 11:26
WARNING : I believe there are a couple of mistakes in the function provided just below by maciej dot strzelecki at gmail dot com. Namely, that in the two substr_replace() calls, the third parameters should respectively be 12 (instead of 11) and 6 (instead of 5).

Considering the importance of this function, I went to read RFC 4122 myself, and found the discrepancy. I therefore chose to write my own function, inspired by the previous one, but with a few enhancements detailed in the comments. On the downside, it might be slightly less easy to understand at first glance.

Please feel free to use it yourself. Thank you also in advance for any feedback at dholmes at cfdsoftware.net .

<?php

/**
 * Generates a Universally Unique IDentifier, version 4.
 *
 * RFC 4122 (http://www.ietf.org/rfc/rfc4122.txt) defines a special type of Globally
 * Unique IDentifiers (GUID), as well as several methods for producing them. One
 * such method, described in section 4.4, is based on truly random or pseudo-random
 * number generators, and is therefore implementable in a language like PHP.
 *
 * We choose to produce pseudo-random numbers with the Mersenne Twister, and to always
 * limit single generated numbers to 16 bits (ie. the decimal value 65535). That is
 * because, even on 32-bit systems, PHP's RAND_MAX will often be the maximum *signed*
 * value, with only the equivalent of 31 significant bits. Producing two 16-bit random
 * numbers to make up a 32-bit one is less efficient, but guarantees that all 32 bits
 * are random.
 *
 * The algorithm for version 4 UUIDs (ie. those based on random number generators)
 * states that all 128 bits separated into the various fields (32 bits, 16 bits, 16 bits,
 * 8 bits and 8 bits, 48 bits) should be random, except : (a) the version number should
 * be the last 4 bits in the 3rd field, and (b) bits 6 and 7 of the 4th field should
 * be 01. We try to conform to that definition as efficiently as possible, generating
 * smaller values where possible, and minimizing the number of base conversions.
 *
 * @copyright  Copyright (c) CFD Labs, 2006. This function may be used freely for
 *              any purpose ; it is distributed without any form of warranty whatsoever.
 * @author      David Holmes <dholmes@cfdsoftware.net>
 *
 * @return  string  A UUID, made up of 32 hex digits and 4 hyphens.
 */

function uuid() {
  
  
// The field names refer to RFC 4122 section 4.1.2

  
return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
      
mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
      
mt_rand(0, 65535), // 16 bits for "time_mid"
      
mt_rand(0, 4095),  // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
      
bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
          
// 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
           // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
           // 8 bits for "clk_seq_low"
      
mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node" 
  
); 
}

?>
maciej dot strzelecki at gmail dot com
17-Apr-2006 02:09
This is an implementation of version 4 UUID, which is generating UUIDs from truly-random numbers.

<?php
/* Copyright 2006 Maciej Strzelecki

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */

function uuid()
{
  
// version 4 UUID
  
return sprintf(
      
'%08x-%04x-%04x-%02x%02x-%012x',
      
mt_rand(),
      
mt_rand(0, 65535),
      
bindec(substr_replace(
          
sprintf('%016b', mt_rand(0, 65535)), '0100', 11, 4)
       ),
      
bindec(substr_replace(sprintf('%08b', mt_rand(0, 255)), '01', 5, 2)),
      
mt_rand(0, 255),
      
mt_rand()
   );
}
?>
04-Apr-2006 02:16
if you're generating UUIDs you should really check out http://www.ietf.org/rfc/rfc4122.txt first ('version 4' UUID, chapter 4.4), as they are not completely random.