My Twitter

URL Shortening Function

January 8th, 2010

Here is a function I use from time to time in my code which I thought I should share. It allows you to quickly shorten URL’s via 6 popular URL shortening websites.

function shorten_url($url, $service=NULL){
		if($service== 'tinyurl'){return get_link('http://tinyurl.com/api-create.php?url='.urlencode($url));}
		elseif($service == 'urly'){return get_link('http://ur.ly/new.txt?href='.urlencode($url));}
		elseif($service == 'isgd'){return get_link('http://is.gd/api.php?longurl='.urlencode($url));}
		elseif($service == 'klam'){return get_link('http://kl.am/api/shorten/?format=text&url='.urlencode($url));}
		elseif($service == 'unu'){return get_link('http://u.nu/unu-api-simple?url='.urlencode($url));}
		else{return get_link('http://api.tr.im/v1/trim_simple?url='.urlencode($url));}
		return $url;
	}

	function get_link($url){
		if(function_exists('curl_init')){
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			//curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
			//curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_URL, $url);
			$result = curl_exec($ch);
			$resultArray = curl_getinfo($ch);
			if ($resultArray['http_code'] == 200){
				return $result;
			} else {
				return FALSE;
			}
			curl_close($ch);
		}elseif(ini_get('allow_url_fopen') == 1){
			return fopen($url, 'r');
		}
		return FALSE;
	}

/* Usage */
echo shorten_url('http://www.fullondesign.co.uk/');
// returns: http://tr.im/JPCz
DeliciousFacebookDigg
TwitterStumbleUponGoogleLinkedInRSS Feed

Leave a Reply