Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP base_convert for shortening URLs

Tags:

url

php

I want to make my urls shorter, similar as tinyurl, or any other url shortning service. I have following type of links:

localhost/test/link.php?id=1000001
localhost/test/link.php?id=1000002

etc.

The ID in the above links are auto-incrementing ID's of the rows from db. The above links are mapped like:

localhost/test/1000001
localhost/test/1000002

Now instead of using the above long IDs, I would like to shorten them. I have found that I can use base_convert() function. For example:

print base_convert(100000000, 10, 36);

//output will be "1njchs"

It looks pretty good, but i want to ask if there is any disadvantage(eg. slow performance or any other) of using this function or is there any better approach to do same thing (eg. make own function to generate random ID strings)?

Thanks.

like image 483
Roman Avatar asked Jul 19 '11 08:07

Roman


2 Answers

The function base_convert is fast enough, but if you want to do better, just store the encoded string inside the database.

like image 144
Gedrox Avatar answered Oct 26 '22 11:10

Gedrox


With base_convert() you can convert the string to a shorter code and then with intval() you create a ID to store item in database

My code snippet:-

$code = base_convert("long string", 10, 36);
$ID= intval($code ,36); 
like image 44
Sici Avatar answered Oct 26 '22 10:10

Sici