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:
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]);
回答2:
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);
回答3:
Use curl, which will not follow redirects by default.
回答4:
see https://stackoverflow.com/a/41680608/7426396
I implemented to get a each line of a plain text file, with one shortened url per line, the according redirect 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);
Have fun and enjoy! pw