Tutorial: How To Create Your Own URL Shortener 52

I’ve been thinking about posting this for a while now. Then came the announcement on Sunday, from URL shortening service tr.im, that they are shutting down, effective immediately. It brought to light the issues with relying on the cloud.

Admittedly, this is not as devastating an announcement as your trusted e-mail, or even photo hosting, service going under. However, social media sites — primarily Twitter — have made URL shorteners almost a necessity, and some users have developed quite a bit of “social capital” in the form of links built and shared using a particular service.

Although tr.im promises to keep existing links active through the end of the year, there is currently no way to create new short URLs, nor is there any way to view information or statistics on any existing tr.im links. Poof, they’re gone. No warning, no recourse.

UPDATE: Tr.im has restored their service. However, this unpredictability only reinforces the call to control your site and your brand.

Okay, so what can you do about it?
Make your own URL shortener.

As you’ll soon see, it’s easy, it’s fun, and puts the you in short URLs.

Requirements

  • Web Server — preferably one you host yourself, with control over basic site settings
  • Web Development Language — using PHP here, but this code can be adapted to ASP.NET, ColdFusion, etc.
  • Database — MySQL featured, but SQL Server, PostgreSQL, etc. would work
  • Ideally, you’ll want a short domain to set this up on.
    www.joesautoglassandspareparts.com kinda defeats the purpose 😉

Examples

Each of the following are short URLs to content on other sites:
http://sean-o.com/babysafe
http://sean-o.com/getwindows7
http://sean-o.com/playtime

Getting Started

As mentioned above, we’ll be using PHP 5.2.x & MySQL 4/5 for this tutorial — as these open-source technologies should be available to most of you.

The first thing you’ll need is a source for your short URLs. Easiest way to do that is with a MySQL database (or new table on your existing site’s database). Here’s the structure I used:

Sean O's Short URL Tutorial: Table Structure

Sean O's Short URL Tutorial: Table Structure

You only really need the first three columns, the rest are for statistics & future use (userID). Add/remove fields as you see fit — perhaps you may want a field for notes?

The Script

We’ll only need one script to accomplish the short URL resolution. Create a file called shortURL.php at the root of your site. (or you may choose a custom name & path)

To begin, the first thing to do is grab the short URL — the segment after the base URL.
e.g. http://sean-o.com/playtime
A little regex (regular expressions) goes a long way here to parse the short URL and strip extraneous characters.

$expectedURL = trim($_SERVER['URL']);
$split = preg_split("{:80\/}",$expectedURL);
$shortURL = $split[1];
// security: strip all but alphanumerics & dashes
$shortURL = preg_replace("/[^a-z0-9-]+/i", "", $shortURL);

Next, we’ll check this string to see if it matches a short URL in our database.

$isShortURL = false;
$result = getLongURL($shortURL);
if ($result) { $isShortURL = true; }
$longURL = $result['longURL'];

Finally, we check to see if our $isShortURL flag is set. If a matching short URL was found, we’ll redirect to it. If not, we’ll display our standard 404.

if ($isShortURL)
{
	redirectTo($longURL, $shortURL);
} else {
	show404();  // no shortURL found, display standard 404 page
}

The Functions

The primary function — get the long URL associated with the passed short URL, if it exists.

function getLongURL($s)
{
	// define these variables for your system
	$host = ""; $user = ""; $pass = ""; $db = "";
	$mysqli = new mysqli($host, $user, $pass, $db);
	// you may just want to fall thru to 404 here if connection error
	if (mysqli_connect_errno()) { die("Unable to connect !"); }
	$query = "SELECT * FROM urls WHERE shorturl = '$s';";
	if ($result = $mysqli->query($query)) {
	    if ($result->num_rows > 0) {
		while($row = $result->fetch_assoc()) {
			return($row);
		}
	    } else {
	    	return false;
	    }
	} else {
		return false;
	}
	$mysqli->close();
}

Perform the URL redirection.

function redirectTo($longURL)
{
	// change this to your domain
	header("Referer: http://www.your-domain-here.com");
	// use a 301 redirect to your destination
	header("Location: $longURL", TRUE, 301);
	exit;
}

Finally, display your standard 404 page here.

function show404()
{
	// display/include your standard 404 page here
	echo "404 Page Not Found.";
	exit;
}

Wire It Up

Okay, so we have the script… now what? Well, the “special sauce” here is the 404 redirect. What we’re simply doing is replacing (or augmenting) your site’s 404 page with one that checks a database for a URL shortcut. If one is listed that matches, redirect to it. If not, display your standard (or not so standard) 404 error message.

You’ll need to modify your site’s existing 404 error page, or (recommended) create a new one. If creating a new one, make sure your site is set to point to this file. For IIS (5/6): Go to your web site, Properties, Custom Errors, 404, Edit Properties… For Apache, edit your .htaccess file thusly: ErrorDocument 404 /shortURL.php. (replace with your custom path as appropriate)

Now, Run With It (Additional, Optional Steps)

If you’ll be using this with any regularity, you’ll probably want to create an admin panel page to quickly add & manage your URLs (I’m simply using a MySQL GUI — the great HeidiSQL). Consider whether you want to use custom short URL names, or just generate a random 4-5 character string (or both!). If you’re a statistics nut, you might want to capture more than just the user’s IP and/or build a stats page.

If you’re looking to “monetize” (ahem, see above), you may want to frame the linked site under a toolbar with your site’s branding, a la the “Digg Bar”. I highly recommend against this, however, as many users consider this practice an annoyance.

If your domain name is longer than, say, 8 characters, consider purchasing a second domain for exclusive short URL serving. Two-letter country-based domains such as .ly and .to are popular. Flickr’s recent purchase of http://flic.kr was especially clever.

Conclusion

So there you have it. Your very own, shiny new, URL shortening service… in under 50 lines of code!

Be sure to test. I suggest trying the following: a short URL you’ve created, a known working URL on your site (make sure you didn’t break anything!), and a known incorrect URL (test the standard 404). Also, be mindful of the security implications. Make sure following best practices with regards to MySQL security, and be sure to sanitize all URLs. Ensure your server is running the latest versions of software with the latest patches.

Disclaimer: This article is just to get you started. The code presented here is most certainly “quick & dirty”, and can surely be optimized. This code may or may not work for you, and I cannot be held responsible for any damage that may occur to your site as a result of implementing this.

If you end up implementing this on your site, I’d love to see it. Post an example here in the comments, or follow me on twitter and hit up @seanodotcom. If you’ve ported this code to other languages/databases, drop me a line.

Thanks for reading,
SEAN O
Follow Sean O (@seanodotcom) on Twitter

Advantages

  • You’re in complete control
  • You can specify random short URLs or custom ones, using related keyword(s)
  • You can collect virtually any statistics you wish
  • Excellent for site branding — your URL appears on every link!

Disadvantages

  • You’re responsible for maintaining uptime — as your site goes, so goes the service
  • You need to build any related services — stats tracking, APIs, user registration, etc.
  • Your site’s subdirectory names will override custom short URLs of the same name
  • Every 404 on your site will incur a database hit — be sure to keep your main site links fresh (Thanks 5Min)
  • Utility varies inversely with the length of the primary domain name

Alternatives

  • Simply use another service — bit.ly, cli.gs, etc. (but that’s no fun, and you’re again vulnerable)
  • Creative use of htaccess or IIS Rewrite

p.s. the short URL for this post is http://sean-o.com/short-URL

http://sean-o.com/short-URL

52 thoughts on “Tutorial: How To Create Your Own URL Shortener

  1. Pingback: TR.IM and URL Shortening | Arid.NET

  2. Reply Suneel Aug 15,2009 1:28 am

    This is the simplest manner I have observed which can be used to create a URL shortener.

    Thanks for posting.

  3. Reply Five Minute Argument Aug 17,2009 7:49 am

    Hi Sean.

    Nice post; a really quick and simple tutorial. I think you should probably add a disclaimer (and an item in the ‘Disadvantages’) that the 404 route will cause a hit to the database on EVERY 404. This is probably not what anyone wants to do.

    You hint at server-related solutions; I’ve had success with the following approach:

    1. Store URLs in a database, much as you have done here.
    2. Generate a very basic text file from that data (and keep it up-to-date)
    3. Use apache’s ‘RewriteMap’ directive (http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritemap) or whatever the IIS equivalent is to handle redirects for that URL.

    Apache will cache that data in memory, and update it whenever the text file changes, so this should be much more efficient.

    Cheers,

    fma.

    P.S. There’s an extraneous ampersand-gt in your getLongURL() code example

  4. Pingback: Tutorial: How To Create Your Own URL Shortener » Sean-O.com

  5. Reply chris Kubica Aug 18,2009 9:59 pm

    can you post a complete php file to use as a template? many thanks!

  6. Reply seano Aug 19,2009 9:21 pm

    @fma: Thanks for the detailed comments. I’ve added your disclaimer (a noteworthy one), and cleaned up the encoding (lousy WP auto-formatting).

    @Chris: I’ll create a .php file from the code blocks above next week, when I’ll have full PC access.

  7. Pingback: Tech Thursday: Archive and track Twitter, URL shorteners and squirreling the web - ComponentGear.com Feed - ComponentGear.com

  8. Reply henrik hammer Aug 20,2009 7:15 am

    If I’ve configured DNS to “*.domain.com”, I assume I can use the script as ‘subdomain short-linking’ as well, like “xyz.domain.com” instead of “domain.com/xyz”, right?

    Any hints what script-changes are needed for this to happen?

    (with some extra tweaks, it might even support both, at the same time?)

  9. Reply seano Aug 23,2009 9:16 pm

    Henrik, I haven’t tested the script with sub-domains. Perhaps this article might be of assistance to you?
    http://help.godaddy.com/article/3352

  10. Pingback: URL-Shortener für den eigenen Webspace | Links, Scripts, Tools, URLs | Dr. Web Magazin

  11. Reply Nicolas Hoizey Nov 3,2009 12:24 pm

    You could also just install http://cas.im/ir/ … 😉

  12. Reply Dave Nov 5,2009 5:21 pm

    I don’t think redirecting from a 404 is a good idea – in fact you can’t do it if you’re using Nginx as your server software. Wouldn’t it be better to just have a page or subdomain set up specifically for short urls? e.g. http://s.sean-o.com/short-URL or http://sean-o.com/s/short-URL

  13. Reply Sharif Khan Dec 8,2009 1:09 am

    I like to use http://l4u.in
    It gives short domains rather than /something.
    It also gives me statistics of total clicks. Great short URL service to use.

    I suggest to this article’s author to add this link as url shorten in this article :)
    Features:

    Visit http://l4u.in to create shortened/redirected URLs to any long URL.
    # AJAX interface;
    # Bulk URL shortening;
    # Password-protected URLs;
    # Temporary URLs;
    # Custom tags;
    # Custom tags for bulk URLs (automatically assigned tags like tag1, tag2, tag3 and so on);
    # Redirects statistic – referer domain, referer page, visitor’s IP (+ link to geographical information about each visitor), date;
    # URLs and hits statistics can be seen even without registration (IP-based authorization);
    # Registered users: edit/delete URLs;
    # Mass upload URLs from file;
    # Export links to CSV file;

    Thanks

  14. Reply winmonaye Dec 24,2009 8:17 pm

    Here is another hosted app to shorten URL for own domain.
    http://get-shorty.com/

  15. Reply Adrian Kosmaczewski Dec 28,2009 12:36 pm

    I’ve written my own URL shortener, as a Rails app,
    http://url.akosma.com/
    and released it as open source code (BSD license):
    http://github.com/akosma/cortito/
    Enjoy!

  16. Reply J.J. Jan 12,2010 4:26 am

    I’ve been looking for a simple way to do this for awhile, even for just shortening our post links on our site. Now our URLs on Twitter look a lot less garbled. Thanks for the post.

  17. Pingback: URL-Shortener-Skripte | datenstreifen.org

  18. Reply Pawel Feb 19,2010 8:53 pm

    $_SERVER[‘URL’]; will not do the job (well for me didnt!)

    Here is the script to get the current url:
    http://www.pawelmartuszewski.co.uk/web_design_articles/web-design/how-to-get-the-current-page-url/

  19. Pingback: Serviciu de prescurtare link-uri pe domeniu propriu de la Google Apps . Studiu de caz: 3ner.ro | Auras. Onlineing

  20. Pingback: LifeStream Digest for February 24th | BryanSays.com

  21. Reply Prashant Mar 27,2010 11:32 pm

    nice post. I was looking for one short URL script.

  22. Reply Jason Mar 30,2010 3:38 pm

    anybody by chance put something together like this using ASP/ASP.NET?

  23. Pingback: Easy Guide To Create Your Own URL Shortener

  24. Reply Alex May 15,2010 3:17 pm

    I like http://paidly.com url shortener it’s works really fast!

  25. Pingback: 10 Best URL Shortener Tutorials | RefreshTheNet

  26. Reply jeyaganesh Aug 31,2010 1:45 pm

    good method for url redirection…
    I had alternate for shortening functions

    http://devlup.com/programming/php/create-url-shortener-php/853/

  27. Reply yongbing Sep 5,2010 10:50 pm

    i love it !!

  28. Reply Blue Sep 14,2010 12:18 am

    Hi Sean, great TUT.

    My question is thus.
    Say we have a form, that when submitted creates a unique ID.
    Which lets say is mysite.com/123456

    Can we also instantaneously without any clicks or input echo back the url shortener for this ID ?

    In essence, we have users who PLACE an advert. The advert gets assigned a unique listing ID, when they submit the form. Can we systematically, return a url shortened that pertains to this ID. Upon succesful form submission ?

    Regards Ste

  29. Reply Craig Dorsey Sep 22,2010 10:00 am

    Great tutorial it will come in handy

  30. Reply yii tutorials Nov 9,2010 2:43 pm

    Nice tutorial! prepare to die bit.ly :)

  31. Reply LxC URL Shortener Nov 11,2010 3:46 am

    Hello,

    Check out LxC URL Shortener
    Let me know if you like it.

    Thank you.

  32. Pingback: 5+ Useful Articles for Everything About URL Shortener | 5oranges

  33. Reply liza Feb 16,2011 1:17 am

    Hi! I wonder if I can change/modify the shortened links or delete them in any case? Is there such a service like that?

  34. Reply seano Feb 28,2011 10:07 am

    Hi Liza, if you’re storing them in a database, you can modify, delete, do whatever you like with your shortened links.

  35. Reply Paul Mar 19,2011 3:28 pm

    How can I set up the sql thing in phpmyadmin?

  36. Reply Alex May 11,2011 8:56 am

    Hello

    I think the best what you can do is to install your own link tracking & URL shortening service on your server (domain) like link-tracking.co.uk/sean-o.tr then you can be sure your hardly created links in years will not get banned or deleted. :)

  37. Pingback: Private URL shortener

  38. Reply Margarita Sep 28,2011 4:31 pm

    I tried to make a url for writter purpose. Help please Thank You

  39. Pingback: Do you know that there is a url shortner already built in WordPress?

  40. Pingback: The Beginner's Guide to Twitter - How To Get Your Company Twitter Account Up And Running.

  41. Pingback: The Beginner’s Guide to Twitter | Sphinx Web Design Experts

  42. Reply dohliz Jul 9,2012 11:26 am

    I was trying to code my own URL using php coding for my new website and by googling the thing I found this post; It’s really worthy!!! Thanks for such post man!

  43. Reply Create Short Link - 2lnkin Jul 14,2012 12:43 pm

    Nice tutorial ! It’s time to make our own short link system :)

  44. Reply ammar aslam Jul 18,2012 10:30 am

    i am not able to create an url shortener anyone could help?

  45. Reply Kedar Jul 26,2012 8:14 am

    You can also use make use of mkdir() for each url.

  46. Reply Rurl Apr 23,2013 9:43 pm

    Very nice explanation… thanks for sharing… also visit rurl.in for url shortner

  47. Reply Manuela Jul 31,2013 11:43 pm

    Sean I have a question,

    First of all congratulation for the post and many many many thanks for what you do. The question I was talking about earlier is how to make money of of it and help others achieve that as well and is there a way to automise it? (or at least a part of it). if I have a stupid question please over look it. nube here. thanks again

    P.S. could you be so kind as to send me a reply to my email address as well? thank you, you are the best

  48. Reply Julian Aug 27,2013 1:44 pm

    Awesome solution. I plan to use this custom url shorter to support multilanguage posts in my blog. What I am doing is adding a subdomain with the language code. Thanks.

  49. Pingback: Creating arbitrary urls that work like redirecting virtual directories - Just just easy answers

Leave a Reply