Skip to content

Instantly share code, notes, and snippets.

@vluzrmos
Last active September 26, 2018 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vluzrmos/2dd39565fc722309bb68d6e87cfda933 to your computer and use it in GitHub Desktop.
Save vluzrmos/2dd39565fc722309bb68d6e87cfda933 to your computer and use it in GitHub Desktop.
PHP URL Resolve HTTP Redirection Recursively
<?php
/*
* Resolver using Guzzle
*/
if (!function_exists('resolve_http_redirection')) {
/**
* @param string $url
* @param int $limit
* @return mixed
*/
function resolve_http_redirection($url, $limit = 10)
{
$location = null;
$client = new \GuzzleHttp\Client([
'on_stats' => function (\GuzzleHttp\TransferStats $stats) use (&$location) {
$location = $stats->getEffectiveUri()->__toString() ?: $location;
},
'verify' => false,
'headers' => [
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
],
'allow_redirects' => [
'max' => $limit,
],
'http_errors' => false,
'cookies' => new \GuzzleHttp\Cookie\CookieJar()
]);
$client->head($url);
return $location ?: $url;
}
}
<?php
if (!function_exists('resolve_http_redirection')) {
/**
* Resolve http redirections.
* Note: the function http_build_url depends on module "pecl_http", see https://github.com/jakeasmith/http_build_url for compatibility
* @param $url
* @param int $limit Redirection Limit
* @return string
*/
function resolve_http_redirection($url, $limit = 10) {
/**
* Segments to fix when the header "Location" is just a path
*/
static $urlSegmentsToFix= [
'host',
'scheme'
];
static $headerLocationLength = 9;
if ($limit < 1) {
return $url;
}
$headers = @get_headers($url);
if ($headers !== false) {
foreach($headers as $header) {
if (stripos($header, 'Location:') === 0) {
$location = parse_url(
trim(
substr($header, $headerLocationLength)
)
);
$parts = parse_url($url);
// Fix location port
if (!isset($location['scheme']) && !isset($location['port']) && isset($parts['port'])) {
$location['port'] = $parts['port'];
}
// Fix url segments (host, scheme ...)
foreach($urlSegmentsToFix as $segment) {
if(!isset($location[$segment]) && isset($parts[$segment])) {
$location[$segment] = $parts[$segment];
}
}
$url = http_build_url($location);
$limit = $limit - 1;
return resolve_http_redirection($url, $limit);
}
}
}
return $url;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment