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
Related
Currently working on lost and found project where users can make a report when they left something behind.
I'm using laravel 5.4, I have some data already on my DB and I have made every requirements according to my client. But in the end, my client want me to add unique report number ticket for every report that has been made. I've googled it but I can't find tutorial that is similar to my case
I'm totally newbie on programming, any help would be much appreciated.
There's a lot of ways you can do so, but the following two sprint to mind:
Use an auto-increment column from your database and add some other stuff to it like the current date and make sure to add a few zeros in there (e.g. 20192208-00001).
$date = new DateTime('now');
echo $id = $date->format('Y-m-d') . "-" . str_pad($ticket->id, 6, "0", STR_PAD_LEFT);
Alternatively you can use a Uuid for this. These are uniquely generated numbers with a near impossible chance of collision. To set this up you'll need a library which supports it composer require ramsey/uuid. Then you can generate your random numbers like so:
$uuid4 = Uuid::uuid4();
echo $uuid4->toString(); // i.e. 25769c6c-d34d-4bfe-ba98-e0ee856f3e7a
You can use Unix Timestamp as your unique filed.
$token = time();
Now add this token when you are saving a new report to database. If you want to make it more unique you can add some more random strings to it like
In Laravel 5.8 You need to use use Illuminate\Support\Str; this first. and then
$token = time().Str::random(5);
In previous versions its like
$token = time().str_random(5);
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.
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
I have a service on the internet where people post pictures and a short string is generated. Only one can be used ever. However, I am getting into duplicates in the database and I am seeing major problems.
Here's what I am using:
$id=rand(10000,99999);
$short_string = base_convert($id,20,36);
What would be the best way to fix it? Check from the database and keep looping till it doesn't match one? What if every possible solution and it goes in an infinite loop?
Increment the last value by a random amount instead of using a random value. Like so:
$results = mysql_query("SELECT * FROM thetable ORDER BY theId DESC LIMIT 1");
$keyToUse = 1;
if($row = mysql_fetch_array($results)) {
$keyToUse = (int)$row['theId'] + rand(1, 100);
}
Then convert the integer key to and from any format, say using base_convert.
Put your PK through an algorithm that generates a unique number from it and put that through your function.
The best bet would be to make sure the image doesn't exist by using the random number generator against the list of images before writing a new image with that number in it.
Try to increase the amount and type of characters by using an algorithm that uses numbers, letters so it increases the combinations that you can have.
Did you try using mt_rand() http://www.php.net/manual/en/function.mt-rand.php. Also you should be increasing the range.
Use md5 http://php.net/manual/en/function.md5.php
The strings produced have no conflict (with large probability).
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