Created
August 17, 2020 17:48
-
-
Save matpratta/13188f6b2fae29a0c559635011149510 to your computer and use it in GitHub Desktop.
π Follows a redirect chain path and either redirects to the final URL or returns it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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