How I can generate the unique ID in laravel? - php

I’m working with my graduation project in Laravel, and want to generate small unique ID "9 char max" ... I don't need UUID because this will generate 36 char which is too long.

You can use PHP function like this:
function unique_code($limit)
{
return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
}
echo unique_code(9);
Output looks like:
s5s108dfc
Here the specifications:
base_convert – Convert a number between arbitrary bases.
sha1 – Calculate the sha1 hash of a string.
uniqid – Generate a
unique ID.
mt_rand – Generate a random value via the Mersenne Twister Random
Number Generator.
Or in Laravel you can use laravel Str library:
just use this:
use Illuminate\Support\Str;
$uniqid = Str::random(9);

You can generate a random string with this library:
use Illuminate\Support\Str;
$id = Str::random(9);

You can use this ,
$unique_id= echo floor(time()-999999999);
this is generating a 9 digit unique value based on time.

Generate custom Unique ID or Code (With Prefix or Suffix Or Both Or Only Unique Id) Or reset your ID after the change of Prefix or Suffix Or Both in laravel framework
Visit https://github.com/SirajCse/laravel-unique-id-generator
Example:
Inv-000001/12/21
UniqueIdGenerator::generate(['table' => 'invoices','field'=>'invoice_id','length' => 16,'prefix' => 'Inv-', 'suffix' => date('/m/y')]);
'table' => 'invoices' [sting table name]
'field'=>'invoice_id' [Default 'id'] [Optional][any string field name]
'length' => 12 [Integer value Id length]
'prefix'=>'Inv-' [Default ''] [Optional] [any string]
'suffix'=>date('/m/y') [Default ''] [Optional][any string]
'reset_on_change'=>false[ Default false] [Optional] [Options are 1.prefix , 2.suffix 3.both 4.false]
uniqueId=000001

in laravel create custom helper method
it will generate sequence random number based on condition
function generateSequenceNumber($tablename, array $conditions = [], string $prefix, int $length = 5): string
{
$model = \DB::table($tablename);
if (is_array($conditions) && count($conditions) > 0) {
$model = $model->where($conditions);
}
return $prefix . str_pad(
($model->count()) + 1,
$length,
'0',
STR_PAD_LEFT
);
}
generateSequenceNumber('tablename',[],'prefix-',5); //prefix-00001
generateSequenceNumber('users',['role' => 'admin'],'admin-',5); //admin-00005
generateSequenceNumber('users',['is_active' => 1,'role' => 'client'],'client-',8);
//client-00000008

Related

Masking an auto incrementing primary key

Currently I have a mysql table that displays information about job opportunities. I have an auto incrementing primary key and I want to encode so it isn't easily recognizable.
So the key "1" would be converted into something short like "AE93DZ".
So for URL purposes it isn't something like somesite.com/view/1
Primary Key Unique Id | Job Name
1 | Gardening at X
2 | Dishwasher at Y
3 | Etc
4 | Etc
The primary key needs to be able to be decoded back into it's original key so I can search the database, eg if the user were to click the post then it needs to pull up that job post.
I have tried using Base64 encoding the key.
public static function encode( $input )
{
$salt= "example_salt";
$encrypted_id = base64_encode($input . $salt);;
return $encrypted_id;
}
public static function decode( $raw )
{
$salt = "example_salt";
$decrypted_id_raw = base64_decode($raw);
$decrypted_id = preg_replace(sprintf('/%s/', $salt), '', $decrypted_id_raw);
return $decrypted_id;
}
The encryption returns something like
OE1ZX1SKJS3KSJNMg==
which is too long and contains "=" signs.
I though that changing the base of the ID and add a offset could give you a nice short way to obfuscate the id. Something like this:
function obfuscate($number)
{
$offset = 12345678;
return strtoupper(base_convert($number + $offset, 10, 36));
}
function deobfuscate($code)
{
$offset = 12345678;
return base_convert($code, 36, 10) - $offset;
}
Here 1 would become 7CLZJ and 9999 would become 7CTP9. The codes are guaranteed to be unique. By converting to base 36 the code would only contain the number 0...9 and the letters A....Z.
Simple but effective. Please make the $offset a field in your class.
This only moves you away from the simple numbers of the id, it does in no way help to secure the id.
If you think that the sequential numbers in base 36 are a problem you can add a factor. For instance the prime number 5197. Like this:
function obfuscate($number)
{
$offset = 73074643;
$factor = 5197;
return strtoupper(base_convert($factor * $number + $offset, 10, 36));
}
function deobfuscate($code)
{
$offset = 73074643;
$factor = 5197;
return intdiv(base_convert($code, 36, 10) - $offset, $factor);
}
Which will make it a lot harder to see any logic in the numbering:
1 = 17ICRK
2 = 17IGRX
3 = 17IKSA
4 = 17IOSN
5 = 17IST0
Base64 encoded values are still easily recongnizable.
You could create a hash of the ID e.g. $hash = hash('crc32', $input);, but a better idea would be to generate UUIDs e.g. $uuid = uniqid(); and use that instead of ID

PHP Generate an unique hash from an IPADDRESS

I have a board and i want to disable registrations instead i want the users to be able to post freely with an unique ID based on their IPAddress
for example:
if "Joe" IP is 200.100.15.117, "Joe" nickname will become the hash function of 200.100.15.117
if "Joe" IP changes he will get another ID, that doesn't matter, i only want one unique ID per IPAddress
There are also two important things :
unique ID must be 8 characters long
hash should be secure, i don't want hackers be abble to crack my
users IPaddresses
I thought in using an MD5 function and then trim it to 8 chars, but how unique is that ? is there a better way ?
You can turn the ip address string to LONG(4 bytes) and do whatever you want next.
see the php function ip2long.
The thing with this is that you cant really diferentiate 2 persons on the same network, so if I post on there, and my dorm neighbour goes to the site, the site thinks he is me.
You should consider using cookies, these can easily be made unique, and AFAIK, can't be hacked remotely.
For the unique ID part, if you are storing the "users" in a database, you could just assign the primary key from your "user" table and use that in the cookie.
If it HAS to be 8 chars long, you could prepend 0's to the ID - e.g. 00000001, 00000002.... Atleast this way its unique, and 8 chars long-
EDIT According to OP comment on this answer.
Code below uses BC Math library to translate a MD5 hash into a Base-90 string. This converts a 32 char string into a 20 char one. This is far from desired 8 chars but it is the minimum string length using ASCII range (it is possible to increase the base to Base-94 by using chars ' " \ [space] but this does not affect to the string length and instead may cause problems while handling data).
$ip = '200.100.15.117';
$hash = md5($ip);
$chars16 = array(
'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
'6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15
);
$base10 = '0';
for ($i = strlen($hash) - 1; $i > 0; $i--) {
$base10 = bcadd($base10, bcmul($chars16[$hash[$i]], bcpow(16, $i)));
}
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,;.:-_+*?!$%&##~^=/<>[](){}`';
$base = (string)strlen($chars);
$baseX = '';
while (bccomp($base10, $base) === 1 || bccomp($base10, $base) === 0) {
$baseX = substr($chars, bcmod($base10, $base), 1) . $baseX;
$base10 = preg_replace('/\.\d*$/', '', bcdiv($base10, $base));
}
$baseX = substr($chars, $base10, 1) . $baseX;
echo $baseX; // Shows: 1BS[JdZf/7J$J{ud&r5i
You can salt the ip address, e.g.
$salt = "e45re%$#";
$ip = "200.111.123.111";
$hash = md5($ip.$salt);
$hash = substr($hash,0,8);

String to hexadecimal Color Code

in a project I'm making I'm using numerous color codes.
the point is not for them to be Beautiful, just differents.(I also want to be able to constantly have the same colors code for the same fields on refresh (no Random color generators))
I was thinking about taking the name of the fields and turn them to Hex color.
Is there a pre-defined function for this?
Exemple :
$string = "Blablabla";
$colorCode = toColorCode($string);
function toColorCode($initial){
/*MAGIC MADNESS*/
return array("R"=>XXX,"G"=>XXX,"B"=>XXX);
}
FORGOT TO MENTION : it's important that the values are Numbers only.
As far as I can understand, you want to generate a fairly unique color code for a string.
The easies way is to call a checksum function on the string, for example MD5:
function toColorCode($initial){
$checksum = md5($initial);
return array(
"R" => hexdec(substr($checksum, 0, 2)),
"G" => hexdec(substr($checksum, 2, 2)),
"B" => hexdec(substr($checksum, 4, 2))
);
}

Which data type is suitable for storing this situation?

For example, I have a user, and the user have different user right, for example, a user can have
-create file
-read file
-update file
-delete file
4 rights, I can use 4 BOOL to find the user right, but if the user have more right, I need create more and more BOOL to store the right. I don't think it is a good idea. And I think of getting a long integer for this... for example, the user can do all the stuff is 1111.
create file is 1000, read file is 100, update is 10, delete is 1. So, if the user only get read file right is 0100.
Is there any better ideas?? Thank you.
I suggest to convert privileges (rights) in binary-state-string and later, store it in database as long integer or hexadecimal string (VARCHAR; for storing a lot of rights).
Example
$privileges_list = array(
0 => 'create_file',
1 => 'read_file',
2 => 'update_file',
3 => 'delete_file',
4 => 'create_pool',
5 => 'vote_in_pool',
6 => 'create_gallery',
7 => 'upload_images',
8 => 'view_statistics'
);
So if you want to set create file, update file and view statistics rights to the user just put 1 on appropriate positions in string (0, 2, 8) and 0 for rest of them
$binary_string = "100000101";
Last character in this string is position 0, first is position 8.
Now you can convert this string to integer (261) or hex-number (105) and put it into database as privilege-set for that user (I prefer hex).
To convert this value back to privileges-list you can use something like this
function hexvalue2privileges($hexvalue, $plist) {
$res = array(); $res_assoc = array();
for ($i = strlen($hexvalue) - 1; $i >= 0; $i--) {
$bin = str_pad(decbin(hexdec(substr($hexvalue, $i, 1))), 4, '0', STR_PAD_LEFT);
$bin_array = array_reverse(str_split($bin, 1));
foreach ($bin_array as $bitstate) $res[] = $bitstate == '1' ? true : false;
}
foreach ($plist as $key => $id) {
$res_assoc[$id] = $res[$key];
}
return $res_assoc;
}
and call this function
print_r(hexvalue2privileges('105', $privileges_list));
Output will be
Array
(
[create_file] => 1 // true
[read_file] => // false
[update_file] => 1 // true
[delete_file] => // false
[create_pool] => // false
[vote_in_pool] => // false
[create_gallery] => // false
[upload_images] => // false
[view_statistics] => 1 // true
)
With every hexadecimal character you can store 4 rights so to calculate number of character needed use this formula
$chars_needed = floor((count($privileges_list)-1) / 4) + 1; // result 3
To get total length of binary-string
$binary_length = $chars_needed * 4; // result 12
To fix length of privileges set
$binary_string = "100000101";
$binary_string = str_pad($binary_string, $binary_length, '0', STR_PAD_LEFT);
// result '000100000101'
To convert $binary_string to hex
$binary_string = "000100000101";
$hexvalue = "";
$groups = str_split($binary_string, 4);
foreach ($groups as $group) $hexvalue .= dechex(bindec($group));
// result $hexvalue='105' (1=0001, 0=0000, 5=0101)
Also you can create groups of privileges and assign them to users by creating privileges-set for every group (administrators, moderators, guests, vip, etc).
Hope this helps
Use [flags CHAR(10) default '0000000000']
Whenever you need any digit, you can use it like
1st digit - New
2nd digit - Edit etc.
At the time of storing, you just need to change that bit and store like this 1100000000. That's it.

How can I obtain the ID from the following example string?

I use the following method to pad out a ID for a property on our website:
function generateAgentRef($id,$length=5,$strPrefix='1'){
return $strPrefix . str_pad($id,$length,0,0);
}
Basically it will prefix 1 and then pad out the id with 0's until the string reaches $length.
But, I now have a requirement to revert this process. For example if I have the following IDs: 100650,100359,100651,100622,100112,100687, how can I get the ID e.g. 650, 359, 651, 622, 112, 687?
Hope this explains what I'm trying to achieve.
The ID in the database will never start with 0, so I was thinking of iterating over the components of the string and detecting when I hit something other than 0 and then splitting the string.
substract 100000 from the generated ref and intval() it could work if the length is 6 numbers exactly.
try using this
$a = substr($num,3);
here $num is the id you get
$a will be your desired number i.e 100659 shortened to 659
Expanding on your initial function
function getAgentId($id, $length = 5, $strPrefix = 1){
return $id - generateAgentRef(0, $length, $strPrefix);
}
$id = generateAgentRef(255);
echo $id, PHP_EOL; // 100255
echo getAgentId($id), PHP_EOL; //255

Categories