How To Build Your Own URL Shortener With Apache, PHP, and MySQL

  • follow us in feedly
Published August 11, 2013 by Brad Knutson
URL Shortener

Short URLs aren’t as popular as they once were, and we can thank Twitter for that. Short URLs were made popular by the 140-character or less update platform where it was necessary to save as much space as possible for text. Of course, now Twitter builds it’s own short URLs, so this practice isn’t exactly necessary – but there are still legitimate uses for it.

Many larger websites have opted to consolidate the authority of their domains by creating and using their own URL shortener. Why pass link juice to a third-party domain when you can create one yourself?

It might seem daunting at first, but I’ll prove to you that it’s really quite simple. We’ll store our full URLs and short URLs in a database, using MySQL and PHP to store and retrieve them. We’ll then use Apache and .htaccess to mask the URL and process the short URL.

Let’s dive in!

Connect.inc

First things first, let’s establish our database connection in an include file. I named this file connect.inc, but it doesn’t really matter what you name it.

<?php
$con = mysql_connect('localhost', 'username', 'password');
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("database_name", $con);
?>

.htaccess

Next, we’ll create a .htaccess file that will take the shortened URLs and send them to a script to be processed.

RewriteEngine On
RewriteRule ^(submit)/?$ submit.php [L]
RewriteRule ^([A-Za-z0-9-]+)/?$ process.php?id=$1 [L]

If you are familiar with Apache and .htaccess files, this probably doesn’t look too out of the ordinary for you.

If this does look like a foreign language to you, then allow me to decode it. Essentially, the third line takes in a URL, such as http://example.com/d9gka, grabs the string after the .com, and sends it to the process.php file as a GET request to be processed. This all happens behind the scenes, and is transparent to the user.

The second line is an exception to this rule, that allows us to hit a script (in this case submit.php) to generate short URLs.

The database

Let’s side-step quickly to see how the database is set up.

I will let you decide how you want to handle how you submit new URLs to be shortened, as it can be done many different ways. You could have a table with predetermined short URL strings that are ready to be assigned, or you could dynamically generate a short URL string. You could also allow the user to create their own short URL. Regardless of how you come up with these values, you’ll need to submit them to the database for storage. Here is the query I use:

$query = "INSERT INTO redirects(id,string,url) values(NULL,'$string','$url')";

The database has three columns:

  • id – Our primary key
  • string – Our short URL string
  • url – Our original, unaltered URL

This table (which I’ve aptly named ‘redirects’) is as simple as it gets. For a more complicated system, you could also add user information (as in who submitted the short URL), timestamps, and more. I am the only person using this service, so I don’t need any of those extra values.

process.php

This is where the magic happens. This script gets the short URL string, and runs a database query to determine if the short URL exists. If it does not, the user is redirected to the submit page, or sent to a not found page.

If the short URL does exist in the database, the user is 301 redirected to the full length URL.

<?php

$id = $_GET&#91;'id'&#93;;

include 'connect.inc';

// determine if short url is valid
$query = "SELECT url FROM redirects WHERE string = '". $id ."'";

$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$url = $row&#91;'url'&#93;;
$num_results = mysql_num_rows($result);

if ( $num_results > 0  ) {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: ". $url );
	exit;
} else {
    // redirect to submit page or short URL not found page.
}
mysql_close($con);
?>

That is essentially it. All that is left to you is to set up a page to submit short URLs to the database.

Live Example

To prove this works, I’ll allow you to test it out using the above code on my own implementation. I bought the short domain inbd.co. Give it a try!

Try The Demo!

It’s really not that complicated once it’s broken down piece by piece. Of course, large-scale operations are much more complicated, but if you have your eye on your own personal URL shortener now you know that it’s more feasible than you might have thought!

Let me know what you think by leaving a comment below!

The following two tabs change content below.
Founder at Inbounderish
Brad Knutson is a Web Developer in the Twin Cities area of Minnesota. He has experience working with WordPress and Drupal, and also has an interest in SEO and Inbound Marketing.

Keep Up-to-Date

Subscribe

Topics

See a complete list of topics discussed in blog posts here.

Check These Out

Get 2 Weeks Free! Sign Up Today! Premium Managed WordPress Hosting Genesis Framework for WordPress SEO is complex. Tools should be simple. Thesis Theme for WordPress:  Options Galore and a Helpful Support Community

20 thoughts on “How To Build Your Own URL Shortener With Apache, PHP, and MySQL

  1. Momin Iqbal

    i m geeting INTERNAL SERVER ERROR………..
    i think there is a problem with htaccess file….
    on second line there is submit.php….but you have not mentioned anything about that file…..so help…………

    Reply
    1. Brad Knutson Post author

      The submit.php file is just a file I use to add new short URLs – it’s just a page with a form and processing script to submit the data to the server.

  2. Loren

    This is great! I am interested in creating a service like this for my college.
    “Of course, large-scale operations are much more complicated…”

    Any ideas of how this could be scaled up or places/services/tools I should look into?

    Reply
    1. Brad Knutson Post author

      I was just getting at the fact that for much larger scale implementations, you would want to make sure that you’re more careful with the PHP and MySQL to ensure your site and database are secure – and you might also want to add data tracking (like click tracking). To replicate something like Bitly would be much more complicated than this simple example.

    1. Brad Knutson Post author

      Hey Fernando,

      This tutorial will walk you through one solution – the solution I used to create a URL shortener. You can use a database to store shortened URLs and their final destinations, but you’ll still need to utilize Apache if you follow this example.

  3. sici

    ok, the code works ok, but there is a maximum limit of shortcodes to generate. they are maximum 5 characters
    as could solve this?

    Reply
    1. Brad Knutson Post author

      Hey Sici,

      Yes there are a limited number of short codes that are 5 characters long. There are such a large number, however, that for this simple example I don’t think you would need to worry about it. Unless you plan on building an enterprise level URL Shortener, 5 characters long should be plenty.

    2. Sici

      I found a very good idea using base_convert () but not on the string, but on the record identifier to store in the database.
      The steps would be: Insert record in db, get the ID and then convert that value into hash

      $rsins = mysql_query(“Insert…etc, etc…
      $id = mysql_insert_id();
      $hash = base_convert($id, 10, 36);

      generates very many hash, hope you like it!!!

    1. sici

      $ins = mysql_query(“Insert into TABLE_NAME (LONG, CODE, DATE_CREATED, COUNTER) values (‘”.$LONG.”‘, ‘”.$CODE.”‘, ‘”.$DATE.”‘,0) “, $DB);

  4. bgocd

    “The database

    Let’s side-step quickly to see how the database is set up.

    I will let you decide how you want to handle how you submit new URLs to be shortened, as it can be done many different ways. You could have a table with predetermined short URL strings that are ready to be assigned, or you could dynamically generate a short URL string. You could also allow the user to create their own short URL. Regardless of how you come up with these values, you’ll need to submit them to the database for storage. Here is the query I use:

    $query = "INSERT INTO redirects(id,string,url) values(NULL,'$string','$url')";"

    I got stuck on that statement, teach me more please…

    Reply
    1. Brad Knutson Post author

      You’ll need to have a base understanding of MySQL databases and how to write queries in order to get this example to work properly. The SQL qucery I used was:

      $query = "INSERT INTO redirects(id,string,url) values(NULL,'$string','$url')";"

      If this looks like a foreign language to you, then I’m not going to be able to teach you to create and manipulate a database very easily (especially in the comments section of this post). If that is the case, then using a service like Bit.ly or another URL shortener will be a better option for you.

    1. Brad Knutson Post author

      Hey Max – I’m not sure what you mean. In my example, I used PHP to generate a random text string, so the short URLs are dynamic in that way.

  5. Vinicius

    Can you give an example of the form code Brad? Because I’m in doubt to implement the submit.php page!

    Reply

Share Your Thoughts

Your email address will not be shown.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">