PHP: Using API to Shorten URL

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.

Download a Sponsored Marketing Whitepaper:
The No-Nonsense Guide to Achieving Omni-Channel Relevance

The No-Nonsense Guide to Achieving Omni-Channel Relevance

Ever since the term “omni-channel” was first coined years ago, marketing technology vendors have over-promised and under-delivered on providing businesses with this holy grail of brand ubiquity. Download Now

One comment

  1. 1