I am looking for a PHP function that creates a short hash out of a string or a file, similar to those URL-shortening websites like tinyurl.com
The hash should not be longer than 8 characters.
I am looking for a PHP function that creates a short hash out of a string or a file, similar to those URL-shortening websites like tinyurl.com
The hash should not be longer than 8 characters.
Easy way with duplicate checking in Database:
I was making a url shortner. In my case I used the "id" of database to create every time a unique short url.
What I did is, first -
Insert Data like "Original url" and "creation date" in db leaving the "short url" empty in db. Then get the "id" from there and pass in the function below.
And then UPDATE value of Short Url Code in Database.
Here I'm using "id" to create short code. Since ID can't be same for multi entries. It's unique hence the Unique Code or Url will be unique.
URL shortening services rather use a auto incremented integer value (like a supplementary database ID) and encode that with Base64 or other encodings to have more information per character (64 instead of just 10 like digits).
Shortest hash is 32 character length, how ever you can use first 8 characters of md5 hash
Update: here is another class found here written by Travell Perkins which takes record number and create short hash for it. 14 digits number produce 8 digit string. By the date you reach this number you become more popular than tinyurl ;)
here is example how to use it:
Best Answer Yet: Smallest Unique "Hash Like" String Given Unique Database ID - PHP Solution, No Third Party Libraries Required.
Here's the code:
TinyURL doesn't hash anything, it uses Base 36 integers (or even base 62, using lower and uppercase letters) to indicate which record to visit.
Base 36 to Integer:
Integer to Base 36:
So then, instead of redirecting to a route like
/url/1234
it becomes/url/ax
instead. This gives you a whole lot more use than a hash will, as there will be no collisions. With this you can easily check if a url exists and return the proper, existing, ID in base 36 without the user knowing that it was already in the database.Don't hash, use other bases for this kind of thing. (It's faster and can be made collision-proof.)