Get Redirect URL with PHP

There are plenty of times when you’ll need to find the final URL after a series of redirects. For single redirects, cURL with CURLOPT_FOLLOWLOCATION set to true does the trick, but it won’t follow multiple redirects. This function will:

<?php

function get_redirect_url($url) {
	if (!array_key_exists('debug',$GLOBALS)) { $GLOBALS['debug'] = false; }
	if ($GLOBALS['debug']) { echo '<p>Looking up URL: '.$url.'</p>'; }
	$original_url = $url;

	$continue = true;
	while ($continue) {

		$url = trim($url);
		if ((substr(strtolower($url),0,7) != 'http://') && (substr(strtolower($url),0,8) != 'https://')) {
			if ($GLOBALS['debug']) { echo '<p class="alert alert-danger">Invalid URL. Returning original URL.</p>'; }
			return $original_url;
		}

		$headers = @get_headers($url);
		if (!$headers) {
			if ($GLOBALS['debug']) { echo '<p class="alert alert-danger">URL did not return any headers. Returning original URL.</p>'; }
			return $original_url;
		}
		
		$new_url = false;
		foreach ($headers as $h) {
			if (substr($h,0,10) == 'Location: ') { $new_url = trim(substr($h,10)); break; }
		}
		
		if ($new_url) { $url = $new_url; $continue = true; }
		else { $continue = false; }
	}

	if ($url) {
		if ($GLOBALS['debug']) { echo '<p>Final URL is: '.$url.'</p>'; }
		return $url;
	} else {
		if ($GLOBALS['debug']) { echo '<p class="alert alert-danger">Could not determine final URL. Returning original URL.</p>'; }
		return $original_url;
	}
}

?>

If you want to see details of what’s happening before you start, set $GLOBALS['debug'] to true before calling the function. Otherwise, all you have to do is copy/paste the function and then call it:

$new_url = get_redirect_url('http://example.com/somepage');

In the above example, assuming that http://example.com/somepage redirects to http://example.com/anotherpage and, from there, to http://example.com/finalpage, the value of $new_url will be http://example.com/finalpage.


Comments

Loading…

This post was published on November 27th, 2016 by Robert James Reese in PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.