Creating Small Urls with PHP
Agile Web Application Development with Yii 1.1 and PHP5
Have you ever wanted to create small URLs like in Twitter? This service is provided by bit.ly and it is the one I normally use for my projects. It allows you to shorten any long URL (ie. http://www.ramirezcobos.com = http://bit.ly/8zivPq -click on it and you will be redirected here) and also gives you click statistiques.
Nevertheless, there are also other providers that allows you to create a small URL on the fly such as tinyurl.com or to.y. If any of you wishes to create small urls through their PHP code here I got a set of functions (using CURL) for you use on your projects:
function getTinyUrl($url){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function getToLyUrl($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);
$data = curl_exec ($ch);
curl_close ($ch);
return $data;
}
Usage
$smallURL = getTinyUrl('http://www.ramirezcobos.com');
echo $smallURL; // will display the small URL
Extras
I include the following function too just in case, as I recommend you to check if URLs are in correct format before using the above functions.
function getParsedUrl($url)
{
$parsed_url = parse_url($url);
if (!isset($parsed_url['scheme']) or $parsed_url['scheme'] != 'http'){
echo 'Unsupported URL sheme given, please just use "HTTP".';
exit();
}
if (!isset($parsed_url['host']) or $parsed_url['host'] == ''){
echo 'Invalid URL given!';
exit();
}
$host = $parsed_url['host'];
$host .= (isset($parsed_url['port']) and !empty($parsed_url['port'])) ? ':'.$parsed_url['port'] : '';
$path = (isset($parsed_url['path']) and !empty($parsed_url['path'])) ? $parsed_url['path'] : '/';
$path .= (isset($parsed_url['query']) and !empty($parsed_url['query'])) ? '?'.$parsed_url['query'] : '';
return 'http://' . $host . $path;
}
Tweet this!