Полное решение с использованием простого file_get_contents
(обратите внимание на параметр in-out $url
):
function get_url_contents_and_final_url(&$url)
{
do
{
$context = stream_context_create(
array(
"http" => array(
"follow_location" => false,
),
)
);
$result = file_get_contents($url, false, $context);
$pattern = "/^Location:\s*(.*)$/i";
$location_headers = preg_grep($pattern, $http_response_header);
if (!empty($location_headers) &&
preg_match($pattern, array_values($location_headers)[0], $matches))
{
$url = $matches[1];
$repeat = true;
}
else
{
$repeat = false;
}
}
while ($repeat);
return $result;
}
Обратите внимание, что это работает только с абсолютным URL в Location
заголовок.Если вам нужно поддерживать относительные URL-адреса, см. PHP: Как разрешить относительный URL-адрес .
Например, если вы используете решение из ответа от @Joyce Babu заменить:
$url = $matches[1];
на:
$url = getAbsoluteURL($matches[1], $url);