1

I need to get the final URL from a short URL without using cURL FOLLOWLOCATION (I'm on a shared hosting) I tried the code below but it results in a "moved here" link instead of an echo:

$ch = curl_init("http://bit.ly/test");
$lastUrl = curl_getinfo($ch);
curl_exec($ch);
echo $lastUrl;

How to get the final URL?

Uli
  • 2,625
  • 10
  • 46
  • 71

5 Answers5

2

You can try this way by using get_headers function in php:

function getMainUrl($url) {
    $headers = get_headers($url, 1);
    return $headers['Location'];
}

echo getMainUrl("http://bit.ly/test");
Vahid Hallaji
  • 7,159
  • 5
  • 42
  • 51
0

$lastUrl is an array of data so you shouldn't be echoing it.

The best way to get the full url is to get the headers of the request using curl_exec() Assign your curl_exec() to a variable and you will see the full url there. Then you need to parse it to get the url from the rest of it.

$headers = curl_exec($ch);

Have a look at this site for help on parsing the headers to get just the URL.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
0

This may helpfull

$location = '';

//initialise the curl
$ch = curl_init("http://bit.ly/test");

//get the headers
curl_setopt($ch, CURLOPT_HEADER, true);

//block browser display
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

//execute the curl
$a = curl_exec($ch);

//find the location of redirects
if(preg_match('#Location: (.*)#', $a, $r))
 $location = trim($r[1]);

 //display the location
 echo $location;
Sundar
  • 4,580
  • 6
  • 35
  • 61
0

From PHP.net :

CURLINFO_EFFECTIVE_URL - Last effective URL

You can get it after executing curl but before closing the channel :

$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
gskema
  • 3,141
  • 2
  • 20
  • 39
0

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

Community
  • 1
  • 1
p-w
  • 1