Search code examples
phpurl-shortener

Bit.ly like shortcode algorithm


I'm trying to make a url shortener for a client. I've got a decent algorithm going right now, the only problem is that if the client was to shorten the same URL for a different promotion it would create the same code.

What can I do to prevent that?

$hash = sha1($this->data[$this->alias]['us_url']);
$this->data[$this->alias]['shortid'] = base_convert(hexdec($hash), 10, 32);

I'd like to be able to create multiple shortcodes for the same url to track it differently.


Solution

  • Same procedure as when creating password hashes: Use some salt.

    $hash = sha1($randomly_generated_salt . $my_url);
    

    Thus, same input strings will create different hashes. The salt should have a decent length to provide enough entropy.

    (Although you wouldn't use sha1 to hash passwords!)