I’m creating a link shortening service and I’m using base64 encoding/decoding of an incremented ID field to create my urls. A url with the ID “6” would be: http://mysite.com/Ng==
I need to also allow users to create a custom url name, like http://mysite.com/music
Here’s my (possibly faulty) approach so far. Help in fixing it would be appreciated.
When someone creates a new link:
- I get the largest link ID from the database (it’s not auto incremented)
- Increment the ID by 1
- Generate a short URL code (http://website.com/%5Bshort url name]) by base64_encoding that ID
- Insert into links table: id, short_url_code, destination_url
When someone creates a new link and passes a custom short URL:
- My plan was base64_decode their custom string and use that as the link ID, but I didn’t realize that you can’t just base64_decode any alphanumeric string and turn it into a number.
Is there a better encoding method that will let me turn any number into a short string, and any string into a number, so I can always lookup short urls (whether custom or autogenerated) by turning the name into a number and querying for a link with an ID equal to that number?
First and foremost, make sure you have unicity constraints in place on the
IDandshort_url_codecolumns.When someone creates a new link:
IDfrom the database (for performance reasons you should really REALLY useautoincrementorSEQUENCE, depending on what your RDBMS offers; otherwise go ahead and selectMAX(ID)+1)http://website.com/[short url name]) fromIDusingbase64_encodeor any other custom or standard encoding schemelinkstable:ID, short_url_code, destination_urlIf the insert fails because of a constraint violation go back to step 1 to try a new
ID; you may have had a violation because:autoincrementorSEQUENCE, and may happen quite often otherwise), and/orshort_url_codehas already been used as a custom URL (this will happen very seldomly unless someone is trying to cause trouble on your site)If the insert succeeded, commit and return the short URL to the user
When someone creates a new link and passes a custom short URL:
IDas in step 2 above, use the customshort_url_codeprovided by the userID: go back to step 1 to try a newIDshort_url_code: return an error to the user asking him to pick a different custom URL, as the short URL he/she provided has already been used