How to redirect url link with php from bit.ly

I am trying to get urls with these bit.ly redirects. I tried to open bit.ly links with file_get_contents , but it already receives content from the redirected site, but how to get its URL?

+4
source share
4 answers

I did not know about the bit.ly API, here's how 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]); 
+8
source

You can request the bit.ly API ( documentation ) for a long URL. You will need your username and API key (which can be found on the 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); 
+6
source

Use curl , which by default will not redirect.

+1
source

see fooobar.com/questions/1308508 / ...

I implemented to get each line of a text file with one shortened URL per line corresponding to a 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

0
source

Source: https://habr.com/ru/post/1308505/


All Articles