why not just use their ID number?
Because user ids do not have the same scheme and are sequential. I want all of my users to have let’s say a 16 chr/digit but unique ref ID. It's not really about security, but here the uniqueness is in the foreground. I just selected MD5 for the staging server. I am open for any other advice.
From the conversation in comments, a good solution would be to generate a unique random key and associate it with the value (such as the database row).
This random key is neither an encryption or a hash. This key is a unique reference variable.
So for each user you have their database membership row, and one column would be "reference_key"; this can be populated when a unique value associated only with this account,
For Example
The below code will generate a unique key and save it to the array value $saver['reference_key']
, you can then insert this into your database when you save your other customer data.
The MySQL column should be UNIQUE
indexed and UTF8mb4
collation and character set.
The reason that the testing checks if the value exists already would be its easier to re roll the value before the MySQL error is triggered when an identical value is tried to be inserted into the UNIQUE column.
function nonce_generator($length = 40)
{
// Source can be any valid characters you want to use.
$source = 'abcdefghijklmnopqrstuvwxyzANCEDFGHIJKLMNOPQRSTUVWXYZ0123456789!-=+';
$max = strlen($source) - 1;
$i = 0;
$output = "";
do {
$output .= $source[random_int(0,$max)];
$i++;
}
while($i < $length);
return $output;
}
...
do {
$found = false;
$saver['reference_key'] = nonce_generator(12); //see function above to generate a key.
$check = $dataBase->getSelect("SELECT COUNT(*) as numb FROM customer WHERE reference_key = ? ", $saver['reference_key']);
if ($check['numb'] > 0) {
// check if key already exists in the database.
$found = true;
}
unset($check);
} while ($found === true);
// once a unique key has been found then save this to the database user.
// along with all other user details.
$dataBase->arrayToSQLInsert("customer", $saver);
Please note that for this code uses customised database interactions and is for illustration purposes ONLY
Advantages:
- Unique key does not reference any other customer data.
- Unique key is not a hash or encryption so can not be 'compromised'.
- Key is assured to be unique.
Disadvantages:
- On very large data sets the
do/while
process of finding a unique value may cause a slight slowdown
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…