Skip to content

Instantly share code, notes, and snippets.

@hayd
Created May 8, 2018 16:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hayd/2269e370e77db54274b4f44598ccaa40 to your computer and use it in GitHub Desktop.
Save hayd/2269e370e77db54274b4f44598ccaa40 to your computer and use it in GitHub Desktop.
Get HTTP redirect destination for a URL in PHP
<?php
// FOLLOW A SINGLE REDIRECT:
// This makes a single request and reads the "Location" header to determine the
// destination. It doesn't check if that location is valid or not.
function get_redirect_target($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = curl_exec($ch);
curl_close($ch);
// Check if there's a Location: header (redirect)
if (preg_match('/^Location: (.+)$/im', $headers, $matches))
return trim($matches[1]);
// If not, there was no redirect so return the original URL
// (Alternatively change this to return false)
return $url;
}
// FOLLOW ALL REDIRECTS:
// This makes multiple requests, following each redirect until it reaches the
// final destination.
function get_redirect_final_target($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
curl_exec($ch);
$target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
if ($target)
return $target;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment