Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash id in url php

Tags:

php

Logged in user on my site can create documents, pretty much like on Google Docs. The document can be made public by the user, or private (defualt). The documents are stored in a database table like this:

| id | title | content | public | owner |
| 1  | asd   | asd     | 1      |  1    |
| 2  | asd   | asd     | 0      |  1    |
| 3  | asd   | asd     | 0      |  2    |

If public equals 1, it is a public document that can be viewed with a link from any user: site.com/documents/id

The thing is, even though documents can be public, I don't want users to be able to just increment the url ID by 1 all the time to access all public documents:

  • site.com/documents/1
  • site.com/documents/2
  • site.com/documents/3

And so on...

So maybe I should hash the ID or something like that? Like so:

<?php echo 'site.com/documents/'.md5($id); ?>

Problem is, I can't figure out which ID it is on server side since it is hashed...

What can I do about my problem?

like image 668
lawls Avatar asked Dec 03 '25 22:12

lawls


1 Answers

Depending on your security requirements, you should ensure that your document IDs are actually random and not guessable. If you simply hash the auto-incrementing ID, the resulting hash may seem random, but once someone notices that you are simply hashing increasing numeric values (and correctly guesses your hashing algorithm), it is easy to guess possible document IDs.

To achieve this, you could simply hash random numbers (make sure that there are no hash collisions in your database), or work with UUIDs (see this question for an example on how to generate them).

In order to map your hashed identifiers to existing documents, simply store the hash alongside the document in your database (best use the hash as primary key).

like image 112
helmbert Avatar answered Dec 06 '25 12:12

helmbert