1

I have a bunch of ids for some content, and I have an url with a GET parameter like this: id=202 (where 202 is the ID of the content the user wants to watch). I want to avoid this, and convert the ID to a string with random characters and numbers, like YouTube does (example: watch?v=QEllLECo4OM), and then convert it again to an integer, so I can fetch the content.

I thought about using a table with every ID and a string, and whenever a user uploads something new, I generate a random string and check it inside that table to avoid repetitions.

Is this the only way of doing it? Or is there a better algorithm for this?

Thanks.

Pacha
  • 1,438
  • 3
  • 23
  • 46
  • Why do you want to this? My guess is that the 'random sequence' in the Youtube-urls isn't random, and just a compressed representation of the id. Rarely that is needed. Take a look at the url of this page of SO, the id is shown here in the url – Erwin Jun 24 '14 at 15:04
  • @Pacha You may find this library useful: https://github.com/thunderer/Numbase . I'm an author, so if you have any questions, I'm happy to help. – Tomasz Kowalczyk Aug 03 '15 at 12:01

3 Answers3

2

There is a library exactly for this task: hashids.

It is not meant to be security library, but to obfuscate numeric IDs from database.

Example:

$hashids = new Hashids(); 
$id = $hashids->encode(1, 2, 3); // o2fXhV 
$numbers = $hashids->decode($id); // [1, 2, 3]
cronfy
  • 1,001
  • 1
  • 15
  • 32
0

You could use php functions as base64_encode (202 => MjAy) and then base64_decode (MjAy => 202). But this is only a bit obfuscating and not "secret" if this is your intention.

hellcode
  • 2,678
  • 1
  • 17
  • 21
-1

The table with ID and random string is much safer. Why?

  1. there is no calculation to reverse the ID
  2. nobody from outside can guess or recalculate the ID
  3. nobody knows how many entries you already have in the database as its random string

If you wish to opt for a shorter number there are options

p.s. to make the custom converter safer you could reorder numbers and chars in the Base62 array (0-9, a-z, A-Z) differently so it wont be obvious which character gets which number

Community
  • 1
  • 1