如何从bit.ly获取重定向url链接与PHP

时间:2010-04-30 21:01:09

标签: php redirect bit.ly

我正在尝试获取那些bit.ly重定向的url链接。我试图打开与file_get_contents的bit.ly链接,但它已经从重定向的网站获取内容,但是如何获取其网址?

4 个答案:

答案 0 :(得分:8)

我没有意识到bit.ly API,这是执行它的原始方法:

$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]);

答案 1 :(得分:6)

您可以查询bit.ly的API(documentation)以获取长网址。您需要使用自己的用户名和API密钥(可在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);

答案 2 :(得分:1)

使用curl,默认情况下不会遵循重定向。

答案 3 :(得分:0)

请参阅https://github.com/johndevs/gradle-vaadin-plugin/wiki/Getting-Started-in-Intellij-IDEA

我实现了获取纯文本文件的每一行,每行有一个缩短的url,相应的重定向url:

<?php
// input: textfile with one bitly shortened url per line
$plain_urls = file_get_contents('in.txt');
$bitly_urls = explode("\r\n", $plain_urls);

// output: where should we write
$w_out = fopen("out.csv", "a+") or die("Unable to open file!");

foreach($bitly_urls as $bitly_url) {
  $c = curl_init($bitly_url);
  curl_setopt($c, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36');
  curl_setopt($c, CURLOPT_FOLLOWLOCATION, 0);
  curl_setopt($c, CURLOPT_HEADER, 1);
  curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 20);
  // curl_setopt($c, CURLOPT_PROXY, 'localhost:9150');
  // curl_setopt($c, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  $r = curl_exec($c);

  // get the redirect url:
  $redirect_url = curl_getinfo($c)['redirect_url'];

  // write output as csv
  $out = '"'.$bitly_url.'";"'.$redirect_url.'"'."\n";
  fwrite($w_out, $out);
}
fclose($w_out);

玩得开心,享受! PW