Warning: mysql_connect(): Headers and client library minor version mismatch. Headers:100519 Library:100236 in /home/andrxvjf/public_etc/classes/database.class.php on line 2
Create Your Own Tiny URL Service with PHP and MySQL - Blog - Andrew Sirianni

Create Your Own Tiny URL Service with PHP and MySQL



Apache/2.4.18 (Ubuntu) Server at dcode.com.au Port 80
" data-via="andrewsirianni">Tweet

Tiny URL is a great tool to allow you to shorten longer links. However, it can also be a great opportunity to track the click-throughs generated by that link to evaluate the level of interest in a link. There are a number of services that can do this for you. However, today, we'll look at how you can create your own Tiny URL service.

Before we begin, you will require the following to create your Tiny URL service:

Now let's look at the logic of what we're trying to do:

  1. Create a unique ID for our link; and
  2. When we use that unique ID in a link, it will re-direct to our longer URL.

So to enable this, first we will need a list of links with a corresponding unique ID.

Step 1: Create the Table

First we'll create a simple table that stores the URL and the unique ID. Below is the SQL that can create a table called turl with the columns:

  `turl_link` varchar(10) NOT NULL,
  `link` text NOT NULL
  PRIMARY KEY (`id`)

Now that we have the table, we are ready to start creating and re-directing links.

Step 2: Create Tiny URLs

Each time we want to shorten a URL, we need to first get a unique ID to assign to the URL. The way to do this is to generate a unique ID then confirm that it does not already exist in the database. The following function can do this:

  * Return a unique ID
  function set_unique_turl_link() {
    # Settings
    $num_chars = 4;     // How long do you want your unique ID to be
    $i = 0;
    $my_keys = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Possible values for the unique ID
    $keys_length = strlen($my_keys);
    $url = '';
    $found_key = false;

    while (!$found_key) {
      # Generate key
      while ($i < $num_chars) {
        $rand_index = mt_rand(0, $keys_length-1);
        $url .= $my_keys[$rand_index];

      $sql = "SELECT `id` FROM `turl` WHERE `turl_link` = '" . $url . "'";
      $all = mysql_query($sql);
      $nbr = mysql_num_rows($all)
      if ($nbr == 0) {
        $found_key = true;

    return $url;

A further step would be to check if the link has already been added to the Database. If so, you can then simply return that unique ID rather than create a new unique ID.

Step 3: Add Tiny URL to the Database

Now that we have the unique ID and the URL, we can create add the entry to the database.

  * Add to DB
  * $turl_link -> unique ID
  * $link   -> URL
  $sql = "INSERT INTO `turl` (`id`,`turl_link`,`link`) VALUES (NULL, '" . $turl_link . "', '" . $link . "')";

Step 4: Create Tiny URL

Now we have create a table of links with associated unique ID's we need to generate a link. In this instance, we will do this under a folder t on the current domain (ie andrewsirianni.com). Therefore all our links will be of the form:


Step 5: Create the Re-Direct

Now we have a Tiny URL, we need a page that can re-direct that URL to the "full-sized" URL. The way to do this is to take the tiny_id as a parameter, check the database and return the full-link, then send the user to that page.

So using our example before:


... first, we need a .htaccess file to ensure that the turl_link is passed as a variable to the script that processes the request. So, add a folder t in the main folder of your hosting directory and add the following:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)$ index.php?turl_link=$1 [NC]

... then create a page index.php in a folder t in the main folder of your hosting file. Then add the following to that file:

  # Step 1: Get ID
  $turl_link = $_GET['turl_link'];

  # Step 2: Check the Database for this turl_link
  // Add your database connection
  $sql = "SELECT `link` FROM `turl` WHERE `turl_link` = '" . mysql_escape_string($turl_link) . "'";
  $all = mysql_query($sql);
  if (mysql_num_rows($all) > 0) {
    // Link exists
    $rd = mysql_fetch_assoc($all);

    #Step 3: Re-Direct the Page to the Link
    header('location: ' . $rd['link']);
  } else {
    // Can't find link
    echo '<p>Cannot find corresponding link.</p>';


This index.php file should now pass the turl_link variable into the script, find the corresponding URL to re-direct to and send the user to the page.

And that's how to create your own, simple Tiny URL service with PHP and MySQL. I hope this has been useful. Please share your comments, suggestions and feedback below.

comments powered by Disqus

About Me

I design & develop software that runs on the Internet. As a qualified analyst, accountant and real estate agent, I can deploy systems that improve performance.


Warning: DOMDocument::load(https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=andrewsirianni&count=5): failed to open stream: HTTP request failed! HTTP/1.0 410 Gone in /home/andrxvjf/public_etc/templates/rmargin/twitter.tpl.php on line 8

Warning: DOMDocument::load(): I/O warning : failed to load external entity "https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=andrewsirianni&count=5" in /home/andrxvjf/public_etc/templates/rmargin/twitter.tpl.php on line 8

Recent Tweets

Follow me: @andrewsirianni

Copyright ©2012 Andrew Sirianni, All Rights Reserved   LinkedIn Profile