Skip to content

Instantly share code, notes, and snippets.

@Gkiokan
Last active May 24, 2019 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gkiokan/7763ca8eaa34555bf9e39b8e23a6d719 to your computer and use it in GitHub Desktop.
Save Gkiokan/7763ca8eaa34555bf9e39b8e23a6d719 to your computer and use it in GitHub Desktop.
PHP Token Generator v2
<?php
/*
Gist: PHP Token Generator v2
Author: Gkiokan Sali
Date: 2019-05-24
Description: Generate a unique token with a special format.
*/
namespace App\Utils;
class Token {
// Generates the Unique Token and returns it.
public static function generate(){
$val = sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0C2f ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
);
return strtoupper($val);
}
public static function short(){
$val = sprintf( '%04x%04x-%04x-%04x-%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0C2f ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000
// mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
);
return strtoupper($val);
}
public static function mix(){
$val = sprintf( '%04x-%03x-%07x-%02x',
mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0C2f ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000
// mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
);
return strtoupper($val);
}
public static function getString($length=12){
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[random_int(0, $max-1)];
}
return strtoupper($token);
}
public static function getToken($length=12, $delimiter='-'){
$token = self::getString($length);
$key_partial_length = 6;
$in_position = 4;
$occurence = ($length / $in_position) - 1;
$token = implode($delimiter, str_split($token, $key_partial_length));
// for($i=0;$i<$occurence;$i++):
// $offset = $i * $in_position + $i * $in_position ;
// $token = $token = substr_replace($token, "-", $offset, 0);
// endfor;
// $token = substr_replace($token, "-", 4, 0);
// $token = substr_replace($token, "-", 9, 0);
// $token = substr_replace($token, "-", 14, 0);
return $token;
}
public static function getSerial($partialCount=[4,3,7,2], $patchStartingHash=false){
$keys = $patchStartingHash ? [strtoupper(sprintf('%04x', mt_rand( 0, 0x0C2f )))] : [];
foreach($partialCount as $k => $length)
$keys[] = self::getString($length);
$token = implode('-', $keys);
return $token;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment