NardCake
NardCake

Reputation: 130

Unique identification string in php

Currently me and my friend are developing a website, for what we will call 'projects' we just have a basic auto increment id in the database used to navigate to projects such as

oururl.com/viewproject?id=1

but we started thinking, if we have alot of posted projects thats going to be a LONG url. So we need to somehow randomly generate a alphanumerical string about 6 characters long. We want the chance of the string being duplicated being extremely low and of course we will query the database before assigning an identifier. Thanks for anyhelp, means alot!

Upvotes: 0

Views: 440

Answers (4)

Raj Adroit
Raj Adroit

Reputation: 3878

You can use this code to generate dynamic 6 digit number....

$random = substr(number_format(time() * rand(),0,'',''),0,6);

Here’s whats happening with the code: The outer portion “substr ” is used to chop down the random number we create to 6 characters. You will notice the number 10 at the end of the snippet, which can be changed to any number you want.

The “number_format ” function helps get rid of the scientific notation that will arise from generating the random number. In the middle, “time() ” and “rand() ” are multiplied. Time() is the number of seconds from January 1 1970, and rand() is a uniquely generated number through PHP.

Always remember that generating unique numbers is not fool proof. If your application requires each number to be unique, perform a collision check in the database before saving.

Upvotes: 0

Brad
Brad

Reputation: 163301

Keep numeric IDs in your database for speed. Use an algorithm that turns those numeric IDs into alphanumeric IDs.

That way, you don't have to worry about duplicates, and you still get really fast indices in your DB.

See this answer: https://stackoverflow.com/a/12479939/362536 And this question: Tinyurl-style unique code: potential algorithm to prevent collisions

Upvotes: 2

Manolis Agkopian
Manolis Agkopian

Reputation: 1094

Try this:

    $id = substr(md5(uniqid()), 0, 6);

Upvotes: 0

Madara's Ghost
Madara's Ghost

Reputation: 174957

You could always use PHP's uniqid() to generate a random string, then trim it down with substr().

$unique_six_character_id = substr(uniqid(), 0, 6);

Upvotes: 0

Related Questions