goo.gl/A4hI How can I be generating an equal ID of this google and verify if it already exists, if it happens generate another. PHP
goo.gl/A4hI How can I be generating an equal ID of this google and verify if it already exists, if it happens generate another. PHP
I confess that I do not know a way to do this automatically. But one solution I thought of was you make an associative table between an ID and the generated characters. You would do a function that would generate these 5 characters, check if these characters are already being used, otherwise save the ID and code in the database.
If you want a function to generate these characters I'm leaving an example here
function gerarCaracteres($tamanho = 5) {
$caracteres = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz';
$retorno = '';
$len = strlen($caracteres);
for ($i = 1; $i <= $tamanho; $i++) {
$rand = mt_rand(1, $len);
$retorno .= $caracteres[$rand-1];
}
return $retorno;
}
There are a few things to consider:
Is it interesting that you hide the number?
If you have /1
, /2
, /3
a user can change the value and get previous values. This is very bad in some cases, for example on YouTube. YouTube allows hidden videos. If they were sequential a user would have high probability of finding those videos. In addition to synchronization problems between servers.
But this is not necessary in all cases.
Is it interesting to use lyrics?
You can generate a random number, only, without converting to letters and symbols. The use of letters and symbols is used because the URL is treated as text.
Typically, you are able to generate 0 to 18,446,744,073,709,551,615 , using only 8 bytes, UINT64 . However, if you have a /18446744073709551614
URL, you will use 20 bytes, precisely because each number will be treated as any letter, an individual byte.
In addition, databases would treat each letter as one byte ( assuming base64 ), and it was worse to find the data and take up more disk space. So using numbers would be the best option.
My suggestion:
To create the URL use:
$int = random_int(PHP_INT_MIN, PHP_INT_MAX);
$base64 = base64_encode(pack('J*', $int));
$base64 = rtrim(strtr($base64, '+/', '-_'), '=');
This code was based on this response . Use $int
to store in database, $base64
to send to user.
Then, to convert again, use:
$url = 'CODIGO-DO-URL';
$base64 = strtr($url, '-_', '+/');
$base64 = base64_decode($base64);
$int = unpack("J*", $base64)[1];
In this way, search the database for $int
. Of course, this may have worse performance, after all there is a cost for conversion. But, the storage space required will be less, this is evident. But, I believe the database is a bigger problem than converting, ie converting base64 to int still has bigger advantages.