August 16, 2012

Unique url from primary key

Question by Prupel

I’m trying to create a URL similar to youtube’s /v=xxx in look and in behavior. In short, users will upload files and be able to access them through that URL. This URL code needs to be some form of the database’s primary key so the page can gather the data needed. I’m new to databases and this is more of a database problem than anything.

In my database I have a auto increment primary key which file data is accessed by. I want to use that number to to create the URL for files. I started looking into different hash functions, but I’m worried about collisions. I don’t want the same URL for two different files.

I also considered using uniqid() as my primary key CHAR(13), and just use that directly. But with this I’m worried about efficiency. Also looking around I can’t seem to find much about it so it’s probably a strange idea. Not to mention I would need to test for collisions when ids are generated which can be inefficient. Auto increment is a lot easier.

Is there any good solution to this? Will either of my ideas work? How can I generate a unique URL from an auto incremented primary key and avoid collisions?

I’m leaning toward my second idea, it won’t be greatly efficient, but the largest performance drawbacks are caused when things need to be added to the database (testing for collisions), which for the end user, only happens once. The other performance drawback will probably be in the actual looking of of chars instead of ints. But I’m mainly worried that it’s bad practice.

EDIT:

A simple solution would to be just to use the auto incremented value directly. Call me picky, but that looks kind of ugly.

Answer by Starx

Generating non colliding short hash will indeed be a headache. So, instead the slug format of Stackoverflow is very promising and is guaranteed to produce non duplicate url.

For example, this very same question has

http://stackoverflow.com/questions/11991785/unique-url-from-primary-key

Here, it has unique primary key and also a title to make it more SE friendly.


However as commented, they are few previously asked question, that might clear out, why? what you are trying is better left out.

  1. How to generate a unique hash for a URL?
  2. Create Tinyurl style hash

Creating short hashes increases the chances a collision a lot, so better user base64 or sha512 functions to create a secured hash.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!