I have a unique identifier for client i generate everytime a client request a service support.
once the id is generate, the id is inserted in the database
here my code:
function makeUnique() {
$start_time = uniqid(microtime(1));
$duration = sprintf('%0.24f', $start_time);
return date('dmYHis').$duration;
}
echo makeUnique();
this output: 071120112032291320715949.928639888763427734375000
for some reason i get 071120112032291320715949 as the number. what am i doing wrong?
you need to remove the "." (dot) in your function. you are probably using an INT which remove numbers after the dot.
return str_replace('.', '', date('dmYHis').$duration);
and make sure the field is big enough - like varchar(50)
my recommendation will be to simply hash the client id using md5
md5($clientid)
and you have the mysql field as a char(32)
You've already got your solution in your code. The php function uniqid() provides... well, a unique ID. If you want to ensure it's really really really really unique (though it's not necessary), just append time() to the end, like so:
return uniqid().time();
This would also return letters mixed in with numbers (higher entropy), like this response:
4eb8895a76edc1320716634
Related
I'm trying to create an increment number licence with the current date of the year + an increment number but i really don't know how to do this i know MYSQl does not support sequences but i would like to know if there is a way to solve the problem
here my controller
public function create(){
$licence = new Licence ;
$licence ->num_licence = Carbon::now()->year -- i would like here to put the current year like 2017 with a random unique number to get the format like 20170001 for exemple !
...
how to acheice this? thanks in advance :)
you can use uniqid function with current year as prefix.
public function create(){
$licence = new Licence ;
$num_liscence_exist=true;
while($num_liscence_exist){
$num_liscence=uniqid(Carbon::now()->year);
if (!Liscence_Table::where('num_liscence', '=',"'".$num_liscence."'")->exists()) {
$liscence->num_liscence=$num_liscence;
$num_liscence_exist=false;
}
}
}
Generate the random id using uniqid() and concatenate with date:
public function create(){
$liscence=new Liscence();
$year = Carbon::now()->year;
$liscence->num_liscence= $year. uniqid();
$liscence->save();
}
using uniqid() get unique number or also you can use time stamp with it:
$liscence=new Liscence();
$year = Carbon::now()->year;
$liscence->num_liscence= $year. strtoupper(uniqid()) . Carbon::now()->timestamp;
$liscence->save();
Will look like : 2017ABC011486543961
A sequence needs to be stored somewhere so I doubt there's a sensible pure-PHP solution. But since you're already using MySQL there's no reason to not use it. I'd create a database table for that, something like:
CREATE TABLE licence_sequence (
sequence_year YEAR NOT NULL,
next_value INT UNSIGNED NOT NULL DEFAULT 1,
PRIMARY KEY (sequence_year, next_value)
)
ENGINE=InnoDB;
(Ugly sequence_year name was chosen to avoid having to quote it every time.)
You then have to manage this from code, including:
Ensuring you have rows for every year as you need them (this can be as simple as populating data for all years for next century).
Ensuring you don't assign the same value to different items.
A rough overview of stuff to consider:
You can (and should) make your licence number a unique index to avoid dupes.
You can use transactions to avoid unnecessary gaps. Transaction should wrap all the operations involved:
Get next sequence number
Save it into new licence
Increment next number
You need to ensure atomic operations in a multi-tasking environment. This is the hardest part. I've been lately being playing with MySQL named locks and they seem to work correctly.
Can I use strtotime("now") as a unique ID in php application as I assume it uses current timestamp and cannot generate the same integer in future?
It is not safe to use strtotime('now') as id
take a look at this code:
$now = strtotime('now');
$anotherNow = strtotime('now');
$sameCounter = 0;
while($anotherNow == $now){
$sameCounter++;
$anotherNow = strtotime('now');
}
echo $sameCounter; //8558
Result is 8558, very not safe, php did 8558 operations during that secondThere's big chance that you'll get the same ID few times.
you can use uniq function instead
Uniq id is itself a php function , you can have this like this
$uniq = uniqid();
you can add more entropy in this
No, don't do that. Although the timestamp is likely to always be different that doesn't mean it's unique. For instance, what would happen if two requests are issued at the same time? You will have two equal timestamp. When choosing unique IDs, you have to be sure that there's no possible cases in which there are equals values. A good solution is having an auto-increment field. That will make sure that your id will never be the same.
I'm using for small projects, like as mini blog or cms.
this function generate 10 digits with unix time
and change every second, if your project not biq and not get high request or inserts you can use this safely.
$UniqID = time();
it create ID with 10 digits like (1462570078)
for other project I use microtime more than time() or other uniq like this
$m=microtime(true);
echo sprintf("%8x%05x\n",floor($m),($m-floor($m))*10000);
My be rare chance we can get duplicates , you can prefix username
Like this echo "$username-".time(); or "$username".time(); or "$userid-".time();
In php already have uniqid .
The uniqid() function generates a unique ID based on the microtime
(current time in microseconds).
For more information please refer official website http://php.net/manual/en/function.uniqid.php
How can I automatically generate a unique, random 6 digit number to insert into a column of a mysql table? The randomly generated number must not already exist in the column.
I am accessing mysql via php.
The table format is like so, with the random number going in the reqnumber column:
id,status,reqnumber
function gen(){
$num = rand(100000,999999);
if($num == ifnumberinyourdatabase){
gen();
}
return $num;
}
You can also use recursive function here.
which check's if number is your database if it is generate new one if not return the unique number
function gen(){
$num = rand(100000,999999);
$query_idgetrs = "SELECT * FROM servicetbl where reqnumber = $num";
$idgetrs = mysql_query($query_idgetrs, $dbconnection) or die(mysql_error());
$row = mysql_num_rows($idgetrs);
if($row >= 1){
gen();
}
return $num;
}
Just generate a random number and then use str_pad():
$myRandom = str_pad(rand(1,999999), 6, '0', STR_PAD_LEFT);
The problem that you're going to run into is that since you require this to be random, there's no way to know if it exists in the table until it's generated. You'd have to make a loop and keep checking in DB.
Put unique constraint on reqnumber field and put error handling code in PHP
Although random is ok, please note that 6 digits only offers 1 million combinations. I'm not sure how long it would be before you started getting duplicate primary key errors.
A much better solution would be to use a unique value. This is very different to a random value as the unique value guarantees to by different every time. MySql has the auto_increment datatype to help you with this. Unfortunately, you are still limited to 1 million entries when using 6 digits.
If you want a totally random, long identifier, check out MySql's UUID function. It will generate a unique string that is guaranteed to never repeat. However it is much longer than 6 characters because that's what it can take to achieve uniqueness.
A part of your table structure must be:
`id` mediumint(6) AUTO_INCREMENT NOT NULL,
PRIMARY KEY (`id`)
If you really need 6 digits always:
ALTER TABLE tbl AUTO_INCREMENT = 100000;
or use
sprintf()
I am developing a mysql database.
I "need" a unique id for each user but it must not auto increment! It is vital it is not auto increment.
So I was thinking of inserting a random number something like mt_rand(5000, 1000000) into my mysql table when a user signs up for my web site to be. This is where I am stuck?!
The id is a unique key on my mysql table specific to each user, as I can not 100% guarantee that inserting mt_rand(5000, 1000000) for the user id will not incoherently clash with another user's id.
Is there a way in which I can use mt_rand(5000, 1000000) and scan the mysql database, and if it returns true that it is unique, then insert it as the user's new ID, upon returning false (somebody already has that id) generate a new id until it becomes unique and then insert it into the mysql database.
I know this is possible I have seen it many times, I have tried with while loops and all sorts, so this place is my last resort.
Thanks
You're better off using this: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
Or using this: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
But if you actually want to do what you are saying, you can just do something like:
$x;
do {
$x = random_number();
"SELECT count(*) FROM table WHERE id = $x"
} while (count != 0);
// $x is now a value that's not in the db
You could use a guid. That's what I've seen done when you can't use an auto number.
http://php.net/manual/en/function.com-create-guid.php
Doesn't this function do what you want (without verification): http://www.php.net/manual/en/function.uniqid.php?
I think you need to approach the problem from a different direction, specifically why a sequence of incrementing numbers is not desired.
If it needs to be an 'opaque' identifier, you can do something like start with a simple incrementing number and then add something around it to make it look like it's not, such as three random numbers on the end. You could go further than that and put some generated letters in front (either random or based on some other algorithm, such as the day of the month they first registered, or which server they hit), then do a simple checksuming algorithm to make another letter for the end. Now someone can't easily guess an ID and you have a way of rejecting one sort of ID before it hits the database. You will need to store the additional data around the ID somewhere, too.
If it needs to be a number that is random and unique, then you need to check the database with the generated ID before you tell the new user. This is where you will run into problems of scale as too small a number space and you will get too many collisions before the check lucks upon an unallocated one. If that is likely, then you will need to divide your ID generation into two parts: the first part is going to be used to find all IDs with that prefix, then you can generate a new one that doesn't exist in the set you got from the DB.
Random string generation... letters, numbers, there are 218 340 105 584 896 combinations for 8 chars.
function randr($j = 8){
$string = "";
for($i=0;$i < $j;$i++){
srand((double)microtime()*1234567);
$x = mt_rand(0,2);
switch($x){
case 0:$string.= chr(mt_rand(97,122));break;
case 1:$string.= chr(mt_rand(65,90));break;
case 2:$string.= chr(mt_rand(48,57));break;
}
}
return $string;
}
Loop...
do{
$id = randr();
$sql = mysql_query("SELECT COUNT(0) FROM table WHERE id = '$id'");
$sql = mysql_fetch_array($sql);
$count = $sql[0];
}while($count != 0);
For starters I always prefer to do all the randomization in php.
function gencode(){
$tempid=mt_rand(5000, 1000000);
$check=mysql_fetch_assoc(mysql_query("SELECT FROM users WHERE id =$tempid",$link));
if($check)gencode();
$reg=mysql_query("INSERT INTO users id VALUES ('$tempid')",$link);
//of course u can check for if $reg then insert successfull
Ahoy Stack Overflow! This be mai first post...
I'm attempting to identify users with a salted unique public key.
Algorithm - Should I use uniqid(), sha256, sha512, something else? All hashes will be salted. NIST recommended SHA256, but I prefer to hear what others might suggest.
Generation - Does hash(SALT + AUTO_INCREMENT_PK + CREATED_TIMESTAMP) suffice? More entropy?
I'd use email, as it is unique for each user, however the user can modify their email address. I was also considering storing signup_email so that hashes would not have to be re-calculated.
MySQL Storage - Currently, our ID's are INT(255) auto_increment primary key's. As stated earlier, potentially hundreds of millions of keys. Depending on the crypto algo, I should have a fixed-size ID. Can I keep INT(255) or should I use CHAR(n)?
---------------------- Thanks for reading :) -------------------------------
One thing: If you don't trust the users with their IDs, sending them over GET or POST will not work; those are all visible to motivated users.
I would use SHA256 using a salt.counter.time string, and use the output to generate GUIDs for the actual id. This would minimize the possibility for collisions.
You will have to use CHAR for MySQL to store GUIDs.
See the comments at http://us2.php.net/manual/en/function.uniqid.php for more in-depth info. AFAIK GUID is not part of the PHP core so you have to fake it a bit.
If you are using user id as the way to allow a user to do anything with your service, if one user "guesses" the user id of another one, he'll be able to do whatever he wants with that one's account ?
You do not have any kind of other password or anything to go along that ?
Well, in that case, you need something quite unique, don't you ;-)
(Hoping I understood the question well -- but that might not be the case -- sorry, if it isn't)
What do you think of using Globally Unique Identifier (like, for instance, 61350955-9755-4AF3-8C19-6DBC42CA69E2) for your users ?
For an example of how they look like, take a look at http://createguid.com/
As a sidenote, that GUID is quite long ; which means lots of bytes in your DB, if you have millions users... So, it probably shouldn't be used as any kind of primary/foreign key.
What about using the smallest possible integer (that fits the number of users you'll have) as primary/foreign key, as that one will be duplicated in many places of the application ; and only have the "long user id" stored only once, in your user table ?
I wrote this class that gives you an unique id of 24 chars, compatible with the id field of MongoDB (and using the same logic to construct it). Might be useful in the future.
<?php
/**
* Generator for Mongo-like ObjectIds in pure PHP
* Author: Mauricio Piacentini
*
* Inspired by https://github.com/justaprogrammer/ObjectId.js
*
*/
class ObjectIdFactory
{
private $_datetime = null;
private $_machine = null;
private $_pid = null;
private $_increment = null;
public function __construct()
{
$this->_machine = str_pad(dechex(rand(0, 16777215)), 6, "0", STR_PAD_LEFT);
$this->_pid = str_pad(dechex(rand(0, 32767)), 4, "0", STR_PAD_LEFT);
$this->_increment = rand(0, 16777215);
//We need a DateTime object to get timestamps, cache it
$this->_datetime = new DateTime();
}
public function getNewId($forcedincrement = null)
{
if (is_null($forcedincrement)) {
$this->_increment++;
if ($this->_increment > 0xffffff) {
$this->_increment = 0;
}
} else {
$this->_increment = $forcedincrement;
}
$timestamp = $this->_datetime->getTimestamp();
$timestamp_final = str_pad(dechex($timestamp), 8, "0", STR_PAD_LEFT);
$increment_final = str_pad(dechex($this->_increment), 6, "0", STR_PAD_LEFT);
return $timestamp_final . $this->_machine . $this->_pid . $increment_final;
}
}
https://github.com/piacentini/ObjectId.php
Have you looked into using a UUID?
A quick google search yields some good resources/links.
Personally I use md5(uniqid(mt_rand(), true)) which will create 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.