URL Shortening using PHP

Monday April 27thPHP, Scripts, Tutorial Category



Yesterday while developing PunBB Twitter extension, Invarbrass of Projanmo Forum helped me by providing some URL shortening snippets for several websites. Those were very simple to use. I am sharing so that it comes to others’ usages.

to.ly
function CompressURL($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://to.ly/api.php?longurl=".urlencode($url));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$shorturl = curl_exec ($ch);
curl_close ($ch);
return $shorturl;
}
echo CompressURL("http://projanmo.com");

TinyURL.com
function tinyurl($url) {
$url = "http://tinyurl.com/api-create.php?url=" . $url;
$tinyurl = file_get_contents($url);
return $tinyurl;
}

bit.ly
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1')
{
//create the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;

//get the url
//could also use cURL here
$response = file_get_contents($bitly);

//parse depending on desired format
if(strtolower($format) == 'json')
{
$json = @json_decode($response,true);
return $json['results'][$url]['shortUrl'];
}
else //xml
{
$xml = simplexml_load_string($response);
return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;

}
}

/* demo */
$short = make_bitly_url('http://projanmo.com','projanmo forum','R_kdfh84jdjf49jdfjd','json');
echo 'The short URL is: '.$short;

Note: To use bit.ly first register on their site and get api key to use their shortening service.

u.nu (Credits: Lelin)
$original_url = 'http://www.google.com/';
$request = 'http://u.nu/unu-api-simple?url=' . urlencode($original_url);
$response = file_get_contents($request);
if (substr($request, 0, 4) == 'http')
{
echo "Shortened URL = $response";
}
else
{
list ($error_code, $error_message) = explode('|', $response);
echo "Error = $error_message ($error_code)";
}

Bookmark: bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark

No related posts.

No Comments Yet

You can be the first to comment!

Leave a comment

bitly fsockopen -

Size

Colors