Good morning!
I’m trying to generate two keys for user accounts, a public key (which the client will see) and a private key (for the system).
Currently I just use substr(str_shuffle()) to generate the keys for testing, but for production I need to be 100% sure that no two keys are the same. Also, the private key should be nearly impossible to guess.
Private key generation
My idea was like this: RandomString + Number. Example: “jHudSbE12” with the unique number.
The code I have so far:
$pKeyPartOne = substr(str_shuffle('qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM'),0,10);
$pKeyPartTwo = 0 //I got stuck here
$finalpKey = $pKeyPartOne.$pKeyPartTwo
The final private key is then inserted into the database.
I want the number to be unique (like Auto_Increment), but I couldn’t figure out how to get the Auto_Increment number in code before it was put into the database (I know I could put it into the database, then retrieve the increment id and update, but I don’t want to do that).
Generation of the public key
The public key must consist of 8 unique digits. My original idea was to just generate an 8-digit string with substr(str_shuffle() and check if it already exists in the database, but that could take a long time, especially if the code keeps generating a string that does exist already.
I thought about using the PHP date() or time() function, but either it wouldn’t be unique or it wouldn’t have the right length. I’ve also considered using Auto_Increment (I know you can set a starting value), but I’d prefer random generation. Is there a better way to do this?
My questions
- How can I get the increment ID of the database entry that will be assigned before the information is entered into the database?
- How do I generate a 100% unique 8-digit numeric string?
Sorry for the confusion and thanks in advance!