Frage

Suppose many users uploading their pics at one time. So how could i generate a unique id for every pic which could never match with other generated id.

$uniqId = time().'_'.rand();

or should is use.

uniqid();
War es hilfreich?

Lösung

Using the uniqid() PHP function will probably be your best method, since no DB is used for files sent.

As per the PHP manual: uniqid — Generate a unique ID.

"Can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond."

Quoted from the PHP manual.

Andere Tipps

The function uniqid() generate a different id each nanosecond so it'll be unique most of the time.

If you expect tons of users uploading at the same time in a shared environment (multiple servers), then it become quite possible for multiple requests to be handled at the same nanosecond across all servers.

The function accepts two arguments to help increase the uniqueness of the result:

  1. The prefix (first argument) could be set to the server name to avoid cross server name collisions.
  2. The "more entropy" (second argument) increases the likelihood that the result will be unique.

For example:

echo uniqid($my_hostname, true);

Besides the server name you can add other sources of entropy such as the user id (if applicable).

If you are using a database to keep track of images, the other way is to use the (auto_increment) primary key which is unique for each row (so, the database takes care of the uniqueness for you)

You can generate uniqueid by mysql table.

create table ids(id int auto_increment primary key);

When users uploading their pics, write sql like this

insert into ids () values();
select last_insert_id();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top