如何从bit.ly php中重定向URL链接 我正在尝试获取指向这些bit.ly重定向的URL链接。我尝试使用file_get_contents打开bit.ly链接,但是它已经从重定向站点获取内容,但是如何获取其URL?

问题描述 投票:0回答:4
我不知道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]);

php http-redirect bit.ly
4个回答
8
投票
您可以查询long url的api(

documentation

)。您将需要用户名和API键(可以在您的
AccountPage
中找到)。

6
投票

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

请参阅

1
投票

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

0
投票
玩得开心并享受! PW

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";


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.