views:

161

answers:

3

I'm trying to get url links to those bit.ly redirects. I've tried to open bit.ly links with file_get_contents but it already gets content from redirected site, but how to get its url?

+1  A: 

Use curl, which will not follow redirects by default.

Matthew Flaschen
+4  A: 

You can query bit.ly's API (documentation) for the long URL. You will need your username and API key (which can be found on your account page).

$endpoint = 'http://api.bit.ly/v3/expand?';
$params   = array(
    'shortUrl' => 'http://bit.ly/aUmUDq',
    'login'    => 'your_bitly_username',
    'apiKey'   => 'your_api_key',
    'format'   => 'txt'
);
$api_url = $endpoint . http_build_query($params);
echo file_get_contents($api_url);
salathe
+3  A: 

I was unaware of the bit.ly API, here is the raw way to do it:

$context = array
(
    'http' => array
    (
        'method' => 'GET',
        'max_redirects' => 1,
    ),
);

@file_get_contents('http://bit.ly/cmUTtb', null, stream_context_create($context));

echo 'Redirect to: ' . str_replace('Location: ', '', $http_response_header[6]);
Alix Axel
Your solution is great, and will work not only with bit.ly. Thanks!
SaltLake