PHP: Using API to Shorten URL

Depositphotos 11843590 s

Just read an article on the benefits and pitfalls of shortening URLs over at SEOmoz. I utilize the API to do this with the SMS WordPress Plugin that I wrote (currently testing and doing well!).

function doCurlRequest($url, $variable, $value) {
$api = $url."?".$variable."=".$value;
$session = curl_init();
curl_setopt($session, CURLOPT_URL, $api);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($session);
return $data; 
function doShortenURL($longurl) {
$url = "";
$variable = "longurl";
$shorturl = doCurlRequest($url, $variable, $longurl);
return $shorturl;

Thought you folks might appreciate an actual code sample. Be sure to replace the funkified quotes that posting this to the blog adds. To use, just add the above functions to your PHP page and then execute like this:


I would probably add a try/catch block just to be sure. This code works with PHP 5+ with the cURL library enabled. If your host doesn't enable cURL, find a new host.

One comment

  1. 1

What do you think?

This site uses Akismet to reduce spam. Learn how your comment data is processed.