Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
๐Ÿ”— Follows a redirect chain path and either redirects to the final URL or returns it
/**
* fn.flatten_redirect_chain.php
* Follows a redirect chain path and either redirects to the final URL or returns it
* Author: Matheus Pratta <github.com/matheusmk3>
* License: 0BSD
* Version: 1.0.0
*
* @param string $destination The URL that is part of a redirect chain and shall be resolved
* @param mixed $redirect The redirect type to be used (301/302) or false for returning the final URL as string
*
* @return string The final URL of the chain, only present when $redirect is false
*/
if (!function_exists('flatten_redirect_chain')) {
function flatten_redirect_chain ($destination, $redirect = 302) {
// Uses cURL to follow all redirects chain
$curl = curl_init($destination);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_exec($curl);
// Extracts the final URL
$url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
// If we are NOT redirecting, return the URL
if (false === $redirect) return $url;
// In other cases, does the HTTP redirect
http_response_code($redirect);
header('Location: ' . $url);
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment