HomePostsGithub

Expanding a shortened URL to its original URL with PHP

The Solution

function getLongUrlFromShortedUrl($url)
{
  $useragent = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, TRUE);
  curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  $a = curl_exec($ch);

  if (preg_match('#Location: (.*)#', $a, $r)) {
    return trim($r[1]);
  }

  if (preg_match('#location: (.*)#', $a, $r)) {
    return trim($r[1]);
  }

  return '';
}

Example

$shortenedUrl = "https://fb.watch/lAGBftKuUN";

echo getLongUrlFromShortedUrl($shortenedUrl);

// Result:
// - https://www.facebook.com/AnimalsFunWorld/videos/3418677615065754/?extid=CL-UNK-UNK-UNK-IOS_GK0T-GK1C&mibextid=2Rb1fB&ref=sharing
<-- Back to Posts