TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

How to create your own URL shortening service

As the usage of Twitter service growing, URL Shortener service has become more and more popular. And more and more third party URL shortening services has been created. In this tutorial, we will create our own simple URL shortening service using Google URL Shortener API. Let us get started!

Prepration

Create two php files called "index.php" and "gen.php".

  1. index.php: this will be the front page.
  2. gen.php: this will be the server side page to interact with Google URL shortener API. We cannot use JavaScript directly (cross domain issue) to get data from Google.
  3. Follow this instruction http://code.google.com/apis/urlshortener/v1/getting_started.html#APIKey to get an API key from Google, this key will be used for query data from Google. So you have to get this key.
  4. Copy and paste image "load.gif" to the same folder as "index.php". This image will be used as the ajax loading indicator.

Create index.php

Create a simple HTML mockup page first for index.php:

<html>
<head>
</head>
<body>
<div id="container">
    <h1>Google URL Shortener</h1>
    <div id="generator">
        <form id="form" action="#" method="post">        
          <fieldset>         
            <input type="text" name="url" id="short">  
            <input type="submit" value="Shorten"></input>   
            <div class="loading"></div>   
          </fieldset>
        </form>
    </div>
</div>
</body>
</html>

This creates a simple form including a text filed and a submit button. It looks similar as blow: img

Next let us add some CSS style to the document to make it look better. Add following CSS style to the header section of the document:

?

<html>
<head>
<style>
body{
    width:100%;
    margin:0px;
    padding:0px;
}
#container{
    font-family: Arial, serif;
    font-size:12px;
    padding-top:20px;
    width:700px;
    margin: auto;  
}
form{
    width:100%;
    padding: 0px;
    margin: 0px;
}
form fieldset{
    padding:20px;
}
form input{
    padding:5px;
    font-size:14px;
}
form input[type=text]{
    float:left;
    width:80%;
    border: 1px solid #CCCCCC;
}
form input[type=submit]{
    width:10%;
    margin-left:5px;
    float:left;
    border: 1px solid #CCCCCC;
    background: #DDDDDD;
    cursor: pointer;
}
div.loading{
    display:none;
    margin:5px;
    float:left;
    width:16px;
    height:16px;
    background-image: url("load.gif");
    background-repeat: no-repeat;
    background-position: top left;
    background-color: transparent;
}
</style>
</head>
<body>
<div id="container">
    <h1>Google URL Shortener</h1>
    <div id="generator">
        <form id="form" action="#" method="post">        
          <fieldset>         
            <input type="text" name="url" id="short">  
            <input type="submit" value="Shorten"></input>   
            <div class="loading"></div>   
          </fieldset>
        </form>
    </div>
</div>
</body>
</html>

We will not explain CSS style here in details, since that will be another big topic. For now, simply copy those CSS properties to your document. And the page should look better. Please note we have also create a "DIV" with class "loading", this CSS class is the ajax loading indicator, by default it will not display, and we will use jQuery to trigger its visibility. Google URL Shortener API tutorial

Last part of "index.php", which is also the most important part. We will use jQuery lib to accomplish ajax operation for us. Copy and paste following JavaScript to the header section of the document, right after CSS style properties. We will explain what it does later.

<html>
<head>
<style>
body{
    width:100%;
    margin:0px;
    padding:0px;
}
#container{
    font-family: Arial, serif;
    font-size:12px;
    padding-top:20px;
    width:700px;
    margin: auto;  
}
form{
    width:100%;
    padding: 0px;
    margin: 0px;
}
form fieldset{
    padding:20px;
}
form input{
    padding:5px;
    font-size:14px;
}
form input[type=text]{
    float:left;
    width:80%;
    border: 1px solid #CCCCCC;
}
form input[type=submit]{
    width:10%;
    margin-left:5px;
    float:left;
    border: 1px solid #CCCCCC;
    background: #DDDDDD;
    cursor: pointer;
}
div.loading{
    display:none;
    margin:5px;
    float:left;
    width:16px;
    height:16px;
    background-image: url("load.gif");
    background-repeat: no-repeat;
    background-position: top left;
    background-color: transparent;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $('#form').submit(function(){          
            $.ajax({
               type: "POST",
               url: "gen.php",
               data: $(this).serialize(),
               beforeSend: function(){
                 $('.loading').show(1);
               },
               complete: function(){
                 $('.loading').hide(1);
               },
               success: function(data){
                 $('#short').val(data);
               }
             });
            return false;
        });
    });
</script>
</head>
<body>
<div id="container">
    <h1>Google URL Shortener</h1>
    <div id="generator">
        <form id="form" action="#" method="post">        
          <fieldset>         
            <input type="text" name="url" id="short">  
            <input type="submit" value="Shorten"></input>   
            <div class="loading"></div>   
          </fieldset>
        </form>
    </div>
</div>
</body>
</html>

Let us take a close look at those JavaScript we have added above:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <!-- setp 1 -->
<script>
    $(document).ready(function(){
        $('#form').submit(function(){           //step 2
            $.ajax({                            //step 3
               type: "POST",
               url: "gen.php",
               data: $(this).serialize(),
               beforeSend: function(){          //step 4
                 $('.loading').show(1);
               },
               complete: function(){            //step 5
                 $('.loading').hide(1);        
               },
               success: function(data){         //step 6
                 $('#short').val(data);
               }
             });
            return false;
        });
    });
</script>
  • step 1: Load jQuery lib from Google CDN.
  • step 2: Attach a event handler when our form is submitted.
  • step 3: Submit form data to "gen.php" with serialized form data using "POST" method.
  • step 4: Show loading DIV before data is sent.
  • step 5: Hide loading DIV when ajax operation is completed.
  • step 6: Show data in text field if ajax is successfully completed.

Now we are done with "index.php", let us move on to "gen.php", the page which deals with Google URL Shortener API.

Create gen.php

Copy and paste following code into "gen.php".

<?php
//1
if(isset($_REQUEST['url'])&&!empty($_REQUEST['url'])){
     
    //2
    $longUrl = $_REQUEST['url'];
    $apiKey  = 'Your-Api-Key';
     
    //3 
    $postData = array('longUrl' => $longUrl, 'key' => $apiKey);
    $jsonData = json_encode($postData);
      
    //4
    $curlObj = curl_init(); 
    curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
    curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curlObj, CURLOPT_HEADER, 0);
    curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt($curlObj, CURLOPT_POST, 1);
    curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
     
    //5
    $response = curl_exec($curlObj);
    $json = json_decode($response);
      
    //6
    curl_close($curlObj);
     
    //7
    if(isset($json->error)){
        echo $json->error->message;
    }else{
        echo $json->id;
    }  
 
}else{
    echo 'Please enter a URL';
}
?>

Before I explain what this code does, please supply your Google API key on line 7.

  1. Proceed the code only when data ($_REQUEST['url']) is posted to this page, otherwise it will echo an error message ("Please enter a URL").
  2. Get long url from $_REQUEST.
  3. Create a json data using long url and the google API key. This JSON data will be posted to Google as required parameters.
  4. Use PHP cURL to communicate with Google API server.
  5. Get data from Google, and decode it from JSON to an object.
  6. Close cURL connection.
  7. Return error message if there is an error returned from Google, otherwise show the shortened URL.

That is all. Now go back to "index.php" from your favorite browser, this simple URL shortening service should be working.

As this is just a simple URL shortening service, there are a lot to improve such as validation and so on. This script is definitely not in production mode yet. It just shows your basic idea of using Google Shortener API to create your own URL shortening service.

Download

You can download this script from my github account.

The End

Thank you for reading this article, and if you have any encountered anything different, have a different solution or think our solution is wrong, do let us know in the comment section. We will be very happy to hear that.

If you like our tutorial, please follow us on Twitter and help spread the word. We need your support to continue.