Home > PHP > URL shortening using PHP

URL shortening using PHP

October 31st, 2011 Leave a comment Go to comments

to.ly and tinyurl.com are the most wanted URL shortening service providers. We can make urls short from their sites also we can use their services through PHP code.

PHP code to short URL using to.ly

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

PHP code to short URL using  tinyurl.com

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

$url = "http://phpxpert.com/";
echo shortit($url);
Categories: PHP Tags: