In this article you’ll get samples of how to Generate Globally Unique Identifier or GUID in Java, PHP and Flutter.
Why Use it?
Globally Unique Identifiers have certain benefits over number/integer based auto incrementing keys and ids.
- They are uniquely and randomly created on multiple devices and servers. This is useful in multi-server architectures and applications that embrace synchronization and independence simultaneously.
- When GUIDs are part of a URL address of some record, they add another layer of security. You will not be able to just manually bump up or down an integer ID.
Generate Java GUID
The Java Programming Language has build-in method for this feature. I’ve extracted a static method like this:
package uuid; import java.util.UUID; public class Tssstete { public static void main(String[] args) { System.out.println(GUID()); } private static String GUID() { return UUID.randomUUID().toString(); } }
Generate GUID with Flutter:
Flutter has a dart.js plugin for generating Universally Unique Identifiers. As such – it is usable on Web, Mobile Platforms, and it will also be usable – probably – out of the box on the Desktop Platforms.
Install it:
dependencies:
uuid: 2.2.2
Import it:
import 'package:uuid/uuid.dart';
And use it:
var uuid = Uuid();
uuid.v4();
PHP uuid
To be honest, I’ve copied it from Stack Overflow, but, it does the job:
<?php function get_guid() { $data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version to 0100 $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set bits 6-7 to 10 return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } echo get_guid(); ?>
JavaScript
At last – the language that will reach potentially all devices is JavaScript (snippet copied from https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid ):
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
Demo of the JavaScript Code: https://programtom.com/dev_examples/guid/guild_js/
A Demonstration of the code is recorded on YouTube: https://youtu.be/0n3OmtiZDOc