2

I want to create a unique string for our users. our site in php.

right now I am using uniqid() for this but it returns a new value every time when I refresh a page. how could I can stop to generate this every time?

can anyone help me?

tutoground
  • 96
  • 7

5 Answers5

1

After working whole night I got a function it generate unique code in guid format and it work for me

function generateGuid($include_braces = false) {
    if (function_exists('com_create_guid')) {
        if ($include_braces === true) {
            return com_create_guid();
        } else {
            return substr(com_create_guid(), 1, 36);
        }
    } else {
        mt_srand((double) microtime() * 10000);
        $charid = strtoupper(md5(uniqid(rand(), true)));

        $guid = substr($charid,  0, 8) . '-' .
                substr($charid,  8, 4) . '-' .
                substr($charid, 12, 4) . '-' .
                substr($charid, 16, 4) . '-' .
                substr($charid, 20, 12);

        if ($include_braces) {
            $guid = '{' . $guid . '}';
        }

        return $guid;
    }
}
tutoground
  • 96
  • 7
0

You could take hash from user identificator (id or/and login) with hash function. For example you md5

echo md5('sectus'); // e60e49ef667707f291844f87abeaebe5
sectus
  • 15,605
  • 5
  • 55
  • 97
0

A GUID is a Globally Unique Identifier, more specifically Microsoft's implementation of the UUID (Universal Unique Identifier) specification.

There is a full spec relating to the UUID that can be found here (wikipedia for ease of reading) http://en.wikipedia.org/wiki/Universally_unique_identifier#Variants_and_versions

I would generally recommend using a tried and tested library for generataing a UUID. By far the best around is Ben Ramsey's UUID which can be found on Github with good documentation.

https://github.com/ramsey/uuid

philipobenito
  • 682
  • 1
  • 4
  • 14
0

The most common way is to use sessions.

A basic way to do this in your case would be:

<?php
session_start();
if (empty($_SESSION['uid'])) {
    $_SESSION['uid'] = uniqid('xyz', true);
}

...rest of your application...

?>

Then in the rest of your code you can reference $_SESSION['uid'] to identify each user, across page loads. Note that the session doesn't last forever (depending on your PHP configuration).

timclutton
  • 12,682
  • 3
  • 33
  • 43
0

From here: How to generate a new GUID?

If you need a very unique ID:

$uid = dechex( microtime(true) * 1000 ) . bin2hex( random_bytes(8) );

If you really need RFC compliance:

$guid = vsprintf('%s%s-%s-4000-8%.3s-%s%s%s0', str_split($uid,4));
Simon Rigét
  • 2,757
  • 5
  • 30
  • 33