Skip to content

Instantly share code, notes, and snippets.

@hotheadhacker
Last active November 7, 2021 17:31
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 hotheadhacker/a8a9745afada43c19d5be54b55509381 to your computer and use it in GitHub Desktop.
Save hotheadhacker/a8a9745afada43c19d5be54b55509381 to your computer and use it in GitHub Desktop.
PHP file to generate random 6 digit unique Alpha Numeric Based a number (id)
// Algo that generates unique number from id of php
// Algo V1.0 by Salman Qureshi (@hotheadhacker) date 08/11/2021
// TODO: Future add timestamp base uniqueness too
public function codeGenerator($id){
// for len 6
//Step 1: Get Base64
$code = base64_encode($id);
//Step 2: Strip '==' if present
$codeStripped = str_replace('=', '', $code);
//Step 3: Compare if string has been stripped and if present convert to ASCII to reduce the code length
if($code !== $codeStripped){
$rand = rand(65,122);
if($rand >90 && $rand <97){ //to ignore non url characters
$ascii = $rand;
}else{
$ascii = chr($rand);
}
$code = $codeStripped. $ascii;
echo $code;
}else{ //no '=' signs present
$code = $codeStripped;
}
//Step 4: Shuffle Characters
$code = str_shuffle($code);
//Step 5: If length if > 6 we will trim it, to make code shorter
if(strlen($code > 6)){
$code = substr($code,0,6);
}
//Step 6: Convert Mix Random Case
for ($i=0, $c=strlen($code); $i<$c; $i++)
$code[$i] = (rand(0, 100) > 50
? strtoupper($code[$i])
: strtolower($code[$i]));
//Step 7: Shuffle again Characters to increase uniquenes
$code = str_shuffle($code);
//Done and Return
return $code;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment