Last active
November 7, 2021 17:31
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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