I have an email address and I want to create a unique ID based on it, so say email is me#email.com that turns into 66wyy7eu
Ive found a close solution http://www.php.net/manual/en/function.uniqid.php#96898 but it needs the input to be numeric
emails are already unique.
You can't guarantee that a hash of the email will always be unique either.
If your using a DB. an auto-increment field will be unique
Check out hash(). This should allow you to generate a sufficiently unique ID based on a string input.
have you read about md5 ?
PHP md5 function
Personally, I would use something like md5() or sha1(). PHP does have a hash() function that allows you to specify the algorithm used: http://php.net/manual/en/function.hash.php
Please see my answer to another question that is of the same nature, the function can be modified accordingly to suite your needs:
PHP random URL names (short URL)
as stated above the email addresses are unique, and if you store them into a database you will get a unique identification number from the Auto-increment column.
With that id you can then use the above function to create a unique hash for that id, and store that in the same row, then you have 2 identifiers for your email address, the ID to use internally and the encrypted key to use as a short URL service.
alternatively there is a simpler approach where as you constantly create random string and then check to see if it is within your database, if the key is within your database then you generate another and check again until you have a unique id.
here's a quick example:
function createRandomID($length = 9)
{
$random = '';
for ($i = 0; $i < $length; $i++)
{
$random .= chr(rand(ord('a'), ord('z')));
}
return $random;
}
and then simply do:
do
{
$id = createRandomID();
}while(!idExists($id));
//Insert $id into our DB along with the email!
Note: The limitations of the characters effects the amount of unique strings it can produce, the more strings you have within your database the higher the loop rate becomes which could increase the load on your DB and result in slower pages for the user.
Related
I have created a function to generate a unique referral code for a user when they sign up, I want to ensure uniqueness so I check if it already exists, if it does then I call the function again recursively:
public function generateUniqueReferralCode()
{
$referral_code = str_random(8);
if(User::where('referral_code', $referral_code)->exists()) {
$referral_code = $this->generateUniqueReferralCode();
}
return $referral_code;
}
My question is, is this computationally expensive? Can it be done in a more efficient way as it has to scan the user table? Lets say we have 1 million users, it will check against 1 million user records if the key already exists.
PHP functions are pretty costly. So I think the following is a little faster (didn't benchmark):
public function generateUniqueReferralCode() {
$referral_code = str_random(8);
while (User::where('referral_code', $referral_code)->exists()) {
$referral_code = str_random(8);
}
return $referral_code;
}
My approach would be a little simpler. Instead of checking all those records for uniqueness, I'll rather generate a random key and plant the primary key of the last record or the record to be generated.
For instance, here's my flow of thoughts
Generate a random key - 1234abc
Fetch the primary key of the last record. Result - 3
Append it to the key - 1234abc3 ( will always be unqiue )
No, a database uses efficient indexing (search trees or hash codes) for efficient lookups, so that the number of records is virtually immaterial.
But why don't you just increment a counter to implicitly guarantee uniqueness ? (And add random salt if you want.)
I have a file sharing website, and every file has a random id. Example for an id: G4t68MgW7
Every upload I create a random id, and check if it's exists (in a loop). There are some issues with that way.
I have to check if this id does exists (Mysql query)
It's a limited range
So how can I can create a unique id without limitation and without checking if it already exists?
Note: I don't use Auto Increment because I want to avoid from bots to reach every file in my website. example of how it looks in the browser: http://www.example.com/file/G4t68MgW7
You can assign timestamp value ie, time() as id. It will be unique always
Well, you more or less gave the answer yourself.
Illustrated with the following pseudocode:
while (true) {
hash = generate_hash();
SQL -> Check if hash found
if (!found) {
break;
}
}
It is pretty easy to implement this. The generate hash could be a simple md5 or it could be a function that builds a random string based on an array of letters. For example something as simple as:
function generate_hash() {
return '$2y$' . substr(md5(time() . 'foo' . rand(0, 1000000) . 'bar'), 0, 15) . 'ydfdf';
}
In 99.999% of all cases, the hash would be unique, so performance should not be an issue here. This also creates more "randomness" than uniqid().
echo substr(uniqid(rand(10,1000),false),rand(0,10),6)
You can have a table of pre-defined identifiers, so you make sure that they are unique in creation time (you don't have to query if they exist; simply insert and don't do anything if the insert fails). When you want a file to be uploaded, get an unused code and mark it as used so it's not used again.
You can also have a cron to check if you're running out of codes, and run the generation script again (increasing the number of characters makes the number of codes virtually unlimited). As this is asynchronous, it won't affect performance.
I want to generate a Unique Code for each project being created. I have an HTML5 webpage that allows user to create new project, each project when created successfully be assigned a unique code.
I am making a Ajax call to the PHP file on the web server which in-turns saves the project details in MySql database. I have a column in the table that stores unique code for each project created.
I am confused how do i create this code ? is it in PHP or shall i do it in MySql. I want it to be a unique code which will be used by the client to distribute to their customers.
I haven't decided on the length of the key yet but it should be around 8 Digits(combination of char & int is fine ). I know i could use HashTable in Java to create this code based on the inputs from user but i am a fresher to PHP/MySql.
Any advise ?
Note: My Aim is that the key should not be repeated
You can use PHP's uniqid() to generate a unique ID. However, this should not be used for security purposes, as explicity stated in the PHP manual. For more info, go here
Example:
$unique_key = uniqid();
echo $unique_key; // Outputs unique alphanumeric key, like 5369adb278516
Generate Code:
// $length is the length of code you want to return
function generate_code($length) {
$charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789012345678900987654321234567890";
return substr(str_shuffle($charset), 0, $length);
}
To get the verification code, it will call user_code_exists() with a parameter of the generated code which is on $code = generate_code(50).
It will check the database if there's at least one row that has the same value, if the row is 0 (code doesn't exist) it will return as true.
// Do generate and verify code existence
$verification_code = "";
while($this->user_code_exists($code = generate_code(50)) == true) {
$verification_code = $code;
break;
}
public function user_code_exists($code) {
$query = $this->db->prepare("SELECT verification_code FROM accounts WHERE verification_code = :verification_code");
$query->execute(array(':verification_code' => $code));
return ($query->rowCount() == 0) ? true : false;
}
On while loop, once it returns true, the variable $verification_code holds the unique generated code.
This is just an overview, I hope this helps.
See the answers given for this question:
What is the best way to create a random hash/string?
In particular, if you want a purely random value (as opposed to, say a hash of the project name) then see the answer by #Gajus Kuizinas, except using base64_encode rather than binhex will give a shorter but still readable value:
base64_encode(mcrypt_create_iv(8, MCRYPT_DEV_URANDOM));
will give you 11 characters: NTM2OWI0YzR
Or if you don't have the mcrypt library installed, try:
base64_encode(hex2bin(uniqid()."0")); // Derived from microtime (the "0" is needed since uniqid() gives an odd number of characters
gives 10 characters: U2m5vF8FAA after discarding the trailing '=='
If you want to be paranoid about the project code never repeating, add a unique index to the column in your MySql table that stores the unique code for each project created, and repeat the number generation if your insert into the table fails.
As noted by #Mark M above, if you are concerned about security or someone masquerading an existing project code, see #Anthony Forloney's answer in the related question link above. In particular:
Numbers used once (NONCE) - They are used on requests to prevent
unauthorized access, they send a secret key and check the key each
time your code is used.
You can check out more at PHP NONCE Library from FullThrottle
Development
I needed to do something similar, a solution to keep unique id and i ended up with a solution to use PHP function time() like this $reference_number = 'BFF-' . time(); you can change the BFF to something that makes more sense to your business logic. This way i dont have to worry about if new id that is being generated was taken up before.
I hope this helps
I'm trying to send a random number to the database for a user/article ID. It is currently using auto increment as a counting system. However, I'd like for the number to be random and unpredictable.
The mt_rand() function in PHP does exactly what I need. Although, my question is what happens when the function returns a number already in use. Of course I can just use a is_null() to check. But if it keeps on picking a number in use I could imagine that that'd slow the operation down.
Any thoughts on what I might be able to do to get around this? Perhaps I'm going at this all wrong.
Also if there's a function that gives letters and numbers that would also help greatly (like Youtube's).
Thanks for reading!
Here is a simple function to create a 10 character long string. The string is built using upper/lowercase text and numbers. Auto increment is definitely the way to go, however, if you are dead set, the function below should help.
<?php
function randomID()
{
$ID = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,10);
echo $ID;
}
randomID();
?>
To make the string longer, change 10 to whatever you like. In terms of ensuring it does not already exist. I would suggest you generate the new ID and then do a search in the database to ensure it does not exist before inserting. Granted this is an extra step in the chain, but unfortunately this is what needs to be done.
Hope this helps
You should always use an auto_increment field as the primary key of your database. Not doing that costs you a great deal in performance. You can certainly create a secondary ID field with your random ID. I'd probably use a hashing function to get the best chance of a random string:
<?php $key = md5(rand(0,999).time().$myItemTitle); // ex. ce4075a3d3f6fd757eb6dd44810cbe14
You should always (in normal use cases) use an auto incremented ID for performance reasons. If you're purpose is to be able to somewhat hide the next post because someone could be guessing for it then you better add some kind of hashed unique field to your database.
Always random (just encrypting ms) :
<?php
$value = time();
$key = "543yretghf436436";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $value, MCRYPT_MODE_ECB);
//if you want even long string change 128 to 256
$encrypted = base64_encode($encrypted);
$encrypted = rtrim($encrypted, '=');
echo $encrypted;
?>
e.g.
Egttu2XhRGdAiXVfszscWg
XlttfR3XaL6pym1uSNY7Kg
YvoKCweUnN8gZyodRYysLA
What you actually want is some "random" key to use as an identifier for the article. I would keep the auto_increment and eigther:
add an column with a "hashkey" or "random key" to identify the article. This poses the "i already have this key" issue (which should not be that large unless you have billions of articles). See some code examples already posted.
create an extra table with pregenerated keys (i.e. 10000 id -> key values) where you can lookup the id by key. If the table runs out you can easily generate new values. This way you don't have to worry about getting "slow" generation speed.
I need help creating something that works similar to launch rock. After someone signs up to my website, they will get a unique link/url to share with their friends. It's important that the URL is unique so I can see how many people have been recruited by a single member.
Please help!
I am using php and mysql, but I don't know if I need something else. I need help with the code. Thanks.
Not sure how much help you need with coding it but you could use the uniqid to generate a Generic ID: PHP: uniqid - Manual
Then just append that id to your URL something like this: http://www.example.com/page.php?id=$uniqueid
My opinion is use MD5 from member's ID who singed up.
The best way to get a Unique URL is to use a Cryptographic Hashing Algorithm such as SHA1
or MD5 to calculate a unique hash from the User ID. You should store this hash in the users table so it can easily be searched.
Then you can share an URL with the hash applied as a GET value ( yourpage.com/page.php?redirect=hashvalue ), and whenever this kind of URL is visited, you can grab the correct user from the database again.
Any reason you cannot use your Member's ID like the SO Member Page or alternatively a GUID.
When a user's account is created, generate a random character string (let's say 10 characters long) and associate it with the account by creating a new column in your MySQL table.
You can use uniqid() to make a unique ID.
But to account for collisions, you might have to run a loop. It would be a miracle if you'd ever have to run the loop twice:
function generateRandomString($length = 10) {
$characters = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[mt_rand(0, strlen($characters))];
}
return $randomString;
}
do {
$id = generateRandomString(10);
} while (mysql_num_rows(mysql_query('SELECT * FROM TABLE WHERE uniq_id = '$id')) != 0);
// $id is now guaranteed to be unique.
Use openssl_random_pseudo_bytes and run through bin2hex to get a real random string and check that it isn't already in use (truely unlikely).
e.g.
$bytes = openssl_random_pseudo_bytes(20); //may be nonprintable characters
$string = bin2hex($bytes);
http://de2.php.net/manual/en/function.openssl-random-pseudo-bytes.php