OK. Agree that bit.ly provides an API for expanding URL’s. The main purpose of our simple exercise here is to use curl functions in PHP to achieve the same. We will write a simple function that will accept a bitly url as parameter. Then we will use curl to get the expanded url.
Below is the full code for function which we will call expandURL.
function expandURL($url)
{
$retVal = 'Error';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if(curl_exec($ch) != false)
{
$response = curl_exec($ch);
if($response != false)
{
$responseInfo = curl_getinfo($ch);
if($responseInfo['http_code'] == 200)
{
$retVal = 'Expanded URL: '.$responseInfo['url'];
}
else if($responseInfo['http_code'] == 404)
{
$retVal = 'URL Not found';
}
else
{
$retVal = 'HTTP error: '.$responseInfo['http_code'];
}
}
else
{
$retVal = curl_error($ch);
}
}
else
{
$retVal = 'cURL error ocurred : '.curl_error($ch);
}
curl_close($ch);
return $retVal;
}
$result = expandURL('http://bit.ly/LoDhO');
echo $result;
How this works?
$retVal is the return value from function. First we initialize a curl session for bitly url using curl_init. Next 2 lines are most important.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
Since our aim is not to display any output directly in browser, we will set CURLOPT_RETURNTRANSFER to 1 (true). It will return the value after curl execution in a string and will not output anything to browser.