This is the final part of the Writing Your Own URL Shortener with the Google URL Shortener API Series.
At this point, you should have a local LAMP installation setup with a basic file structure and and UI for the URL shortener. Now we need to actually write the code that makes all of this possible.
We’ll start with setting up the necessary PHP code to make the request to Google’s API and then we’ll hook the UI up to the PHP using JavaScript.
1. Sending and Receiving Data via Google
The Google URL Shortener API documentation provides in-depth of examples of how to perform a variety of actions. We’re primarily concerned with shortening URL’s and expanding URL’s.
In order to make these requests, we’re going to leverage PHP’s cURL library. If you’re familiar with it, great; if not, no big deal. I’ll cover all you need to know.
Finally, we need to consider the data that the user provides that we’ll need to handle in our PHP:
- The user may provide a long URL to shorten
- The user may also be providing a short URL to expand
In Part 1 of this series, we talked about providing various input fields and buttons for triggering these actions. I also mentioned to make sure that you provided unique ID’s. This is where it comes in handy.
2. Constants and Requests
Before writing our functions, we need to think about some of the stuff that we’re going to be using throughout the requests.
- We know that we’ll be using the Google API URL and our API to make requests
- We also know that we’re going to be looking at some incoming data to determine if we’re dealing with a long URL or a short URL
Let’s write some PHP to handle this stuff. First, we’ll define a few constants to make our code cleaner through the remainder of the script.
First, let’s define the Google API URL and our API key:
[cc lang=”php”]
define(‘GOOGLE_URL’, ‘http://www.googleapis.com/urlshortener/v1/url’);
define(‘GOOGLE_API_KEY’, ‘YOUR_API_KEY’);
[/cc]
Next, let’s go ahead and store the incoming request data for our URL’s:
[cc lang=”php”]
$longUrl = $_POST[‘longUrl’];
$shortUrl = $_GET[‘shortUrl’];
[/cc]
While we’re at it, let’s go ahead and write a conditional that will help us determine if we’re shortening or expanding URL’s:
[cc lang=”php”]
if(isset($longUrl)) {
// TODO: shorten the URL
} elseif(isset($shortUrl)) {
// TODO: expand the URL
} else {
echo ‘You must enter a URL.’;
} // end if/else
[/cc]
Since we don’t have the proper functionality to perform any actions on the URL right now, it’s a good practice to leave TODO’s in the code. This will allow us to find all of the areas that we have left to stub out during development.
Note that if you’re not familiar with the isset, $_GET, or $_POST functions, the PHP manual is a great resource.
2. Shortening URL’s
Now, let’s go ahead and write our function that’s going to shorten the URL’s.
According to the API documentation for shotening URL’s, this is what’s required:
POST http://www.googleapis.com/urlshortener/v1/url Content-Type: application/json {"longUrl": "http://www.google.com/"}
Let’s translate this into code. We need..
- A function that will accept a long URL
- To set the proper parameters in cURL to execute the request
- Make the request
- Return the data
Here’s how we can do that:
[cc lang=”php”]
function shorten($long_url) {
$ch = curl_init(GOOGLE_URL . ‘?key=’ . GOOGLE_API_KEY);
curl_setopt_array(
$ch,
array(
CURLOPT_HTTPHEADER => array(‘Content-Type: application/json’),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 0,
CURLOPT_POST => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_POSTFIELDS => ‘{“longUrl”: “‘ . $long_url . ‘”}’
)
);
$json_response = json_decode(curl_exec($ch), true);
return $json_response[‘id’] ? $json_response[‘id’] : $long_url;
} // end shorten
[/cc]
Covering the cURL library is beyond the scope of this tutorial. But this particular function will accept a long URL, make the request to the Google URL API via cURL, and then return the request.
At this point, we can update the first TODO in our conditional statement from above. It should now read:
[cc lang=”php”]
if(isset($longUrl)) {
echo shorten($longUrl);
} elseif(isset($shortUrl)) {
// TODO: expand the URL
} else {
echo ‘You must enter a URL.’;
} // end if/else
[/cc]
3. Expanding URL’s
Next, we need to write a function that will expand a URL. According to the API documentation, this is achieved by sending a GET request with the shortened URL:
GET http://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS
Just like the shorten function above, let’s convert this code. We need…
- To accept an incoming long URL
- Configure cURL with the proper parameters
- Make the request
- Return the expanded URL
Here’s how we can write a function to do that:
[cc lang=”php”]
function expand($short_url) {
$ch = curl_init(GOOGLE_URL . ‘?key=’ . GOOGLE_API_KEY . ‘&shortUrl=’ . $short_url);
curl_setopt_array(
$ch,
array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 0,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
)
);
$json_response = json_decode(curl_exec($ch), true);
return $json_response[‘longUrl’] ? $json_response[‘longUrl’] : $short_url;
} // end expand
[/cc]
Finally, we can update the final TODO in the conditional from the first step:
[cc lang=”php”]
if(isset($longUrl)) {
echo shorten($longUrl);
} elseif(isset($shortUrl)) {
echo expand($shortUrl);
} else {
echo ‘You must enter a URL.’;
} // end if/else
[/cc]
Now, save this file and drop it in your PHP directory. I named mine curl.php but feel free to name it whatever.
Here’s the complete PHP source code:
[cc lang=”php”]
array(‘Content-Type: application/json’),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 0,
CURLOPT_POST => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_POSTFIELDS => ‘{“longUrl”: “‘ . $long_url . ‘”}’
)
);
$json_response = json_decode(curl_exec($ch), true);
return $json_response[‘id’] ? $json_response[‘id’] : $long_url;
} // end shorten
/**
* Expands the short URL using the Google shorten API.
*
* @short_url The URL to expand.
*/
function expand($short_url) {
$ch = curl_init(GOOGLE_URL . ‘?key=’ . GOOGLE_API_KEY . ‘&shortUrl=’ . $short_url);
curl_setopt_array(
$ch,
array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 0,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
)
);
$json_response = json_decode(curl_exec($ch), true);
return $json_response[‘longUrl’] ? $json_response[‘longUrl’] : $short_url;
} // end expand
?>
[/cc]
Just make note of your filename – we need it in the final step!
4. Put It All Together
Finally, we need to hook up the UI to the PHP script that will be requesting data and returning it back to the user. To do this, we’ll write some jQuery-based JavaScript.
Essentially, the script should:
- Note which link was clicked (are you expanding or shortening?)
- Grab the value from the relevant input box
- Once the request is complete, drop the result on the UI
Easy enough, right? Let’s start with shortening the URL. Here, you’re going to need the ID of the button you created for shortening the URL, the ID for the input field of the long URL, and the ID of the element that will display the shortened URL.
Here’s the relevant JavaScript. Remember that shortening URL’s requires a POST request and our PHP file is expecting the long URL to be sent via POST:
[cc lang=”javascript”]
$(‘#shorten-url’).click(function(evt) {
evt.preventDefault();
if($(‘#long-url’).length === 0 || $(‘#long-url’).val() === ”) {
alert(‘You need to enter a URL to shorten.’);
} else {
$.ajax({
type: ‘POST’,
url: ‘php/curl.php’,
data: ‘longUrl=’ + $(‘#long-url’).val(),
success: function(data) {
$(‘#shortened-url’).html(data);
}
});
} // end if/else
});
[/cc]
Next, we need to write code for expanding a URL. Again, you’ll need the ID’s of the input field, button, and display for the expanding of the URL. Note that expanding URL’s requires a GET request.
[cc lang=”javascript”]
$(‘#expand-url’).click(function(evt) {
evt.preventDefault();
if($(‘#short-url’).length === 0 || $(‘#short-url’).val() === ”) {
alert(‘You need to enter a URL to expand.’);
} else {
$.ajax({
type: ‘GET’,
url: ‘php/curl.php’,
data: ‘shortUrl=’ + $(‘#short-url’).val(),
success: function(data) {
$(‘#lengthened-url’).html(data);
}
});
} // end if/else
});
[/cc]
Finally, we want the event handlers to be attached as soon as the DOM is ready, so let’s wrap everything in jQuery’s document.ready() funciton. Here’s the complete JavaScript source:
[cc lang=”javascript”]
$(function() {
$(‘#shorten-url’).click(function(evt) {
evt.preventDefault();
if($(‘#long-url’).length === 0 || $(‘#long-url’).val() === ”) {
alert(‘You need to enter a URL to shorten.’);
} else {
$.ajax({
type: ‘POST’,
url: ‘php/curl.php’,
data: ‘longUrl=’ + $(‘#long-url’).val(),
success: function(data) {
$(‘#shortened-url’).html(data);
}
});
} // end if/else
});
$(‘#expand-url’).click(function(evt) {
evt.preventDefault();
if($(‘#short-url’).length === 0 || $(‘#short-url’).val() === ”) {
alert(‘You need to enter a URL to expand.’);
} else {
$.ajax({
type: ‘GET’,
url: ‘php/curl.php’,
data: ‘shortUrl=’ + $(‘#short-url’).val(),
success: function(data) {
$(‘#lengthened-url’).html(data);
}
});
} // end if/else
});
});
[/cc]
That’s it! You should have a fully functioning application. You can download a full, working example here or browse the source on GitHub.
Remember that you’ll need to substitute your API key into the proper place in the PHP file.
Andrew Mason says
Pimp.
Zencoder says
You are a rockstar.
Thank you.
Tom McFarlin says
🙂
Charlie says
Hi Tom,
This is an awesome tutorial!
Any idea what could cause this?
PHP Notice: Undefined index: id in …\tommcfarlin-googleURLShortenerDemo\php\curl.php on line 56
Thanks for any help.
Tom McFarlin says
This means that the array that you’re trying to read has an index that hasn’t been initialized.
For example, if you have an array:
$array = array();
And you try to read:
$array['name']
You’ll get that notice because ‘name’ hasn’t been initialized.
Brittney says
Does this code work in google app scripts?
I would like to pull a shortened url and clicks into a google spreadsheet.