4

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

4

4 回答 4

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]);
于 2010-04-30T21:15:15.800 回答
6

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);
于 2010-04-30T21:11:50.733 回答
1

Use curl, which will not follow redirects by default.

于 2010-04-30T21:05:33.153 回答
0

https://stackoverflow.com/a/41680608/7426396

我实现了获取纯文本文件的每一行,每行有一个缩短的 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);

玩得开心,享受!密码

于 2017-01-16T16:19:46.273 回答