I'm trying to use PHP as a way to process this in a webpage, my typical language is java so i am unfamiliar with how this would be done for product keys.
This is basically the process:
1. Generate random string with format XX-XXXX-XXXX-XXX a mix of numbers and letters.
2. Check if it already exists in an SQL database
3. If exists, generate another one and repeat?
So how would I do this using PHP? Please explain what i would need to do and what is the best way of going about it.
Generate random string from following function.
<?php
function randomString() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
$array_lengths = array(2,4,4,3);
foreach($array_lengths as $v){
for ($i = 0; $i < $v; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$pass[] = '-';
}
return rtrim(implode($pass),'-'); //turn the array into a string
}
echo randomString();
?>
SQL
Please create unique key
field and use ON DUPLICATE KEY
query for insert/ update data
DEMO
You can generates randomnumbers key using this way.
echo rk(2)."-".rk(4)."-".rk(4)."-".rk(3);
function rk($chars) {
$letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
return substr(str_shuffle($letters), 0, $chars);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With