$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]);
documentation
)。您将需要用户名和API键(可以在您的AccountPage中找到)。
使用Curl,默认情况下不会遵循重定向。
请参阅I实施以获取纯文本文件的每一行,每行缩短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);
thanks to alix用于通用解决方案。这是一个不取决于位置标题处于固定位置的版本。
$context = array
(
'http' => array
(
'method' => 'GET',
'max_redirects' => 1,
)
);
@file_get_contents('https://YOUR-SHORTCUT-URL', null, stream_context_create($context));
$urlRedirect = NULL;
foreach ($http_response_header AS $header)
{
$rec = explode(': ', $header);
if (count($rec) == 2 && $rec[0] == 'Location')
$urlRedirect = $rec[1];
}
if ($urlRedirect != NULL)
echo "redirects to $urlRedirect";