What is needed to write your own URL shortener? [closed]
I want to write my own URL shortener using php and mysql as a tester to see how much I know about the two languages? However I don't know what is needed to do so or where to start. Please could someone give me a list of what needs to be done in order to create/write a successful URL shortener?
All you need is a short domain name.
Then you can have a simple MySQL table with two columns: Id (the primary key with auto increment) and Url. Which should probably be a TEXT or something. Since varchar 255 might be too short.
Then set up your .htaccess so that a url like domain.com/a21s1 gets converted to domain.com?url=a21s1
That'd be something along the lines of:
RewriteRule ^(?:.*)domain\.com/(.*)/?$ domain.com?url=$1
Then in php do something like:
if(isset($_GET['url'])){
$url = base_convert((int)$_GET['url'],36,10);
$result = mysql_query('SELECT `Url` FROM `My Table` WHERE `Id` = '.$url);
$row = mysql_fetch_row($result);
$url = $row[0];
}else
$url = 'http://domain.com/yourhomepage';
header('location: '.$url);
You'd also want to have sanity checks when users input a new url to add you would regex it to make sure it's a url, and if it's missing http://
prepend it to the url.
I just done my-gplus
- use as short domain as possible
- use .htaccess rewrites to create short tail after /
- do not bother users with "Thank you for using ... redirecting to" when user is being redirected
- do not force users to register
- allow users to register & view their statistics
.htaccess could look like this
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^(.+)$ redirect.php?url=$1 [L]
精彩评论