Get the first and final redirect location from redirect chain

Redirect chain

What is Redirect Chain?

A redirect chain refers to a series of consecutive redirects that occur when a web page or URL is accessed. In a redirect chain, the initial URL is redirected to another URL, and this process may repeat multiple times until the final destination URL is reached. Each step in the chain involves an HTTP redirect response, typically with status codes like 301 (permanent redirect) or 302 (temporary redirect).

For example:
  1. The browser accesses URL A.
  2. URL A responds with a redirect to URL B.
  3. URL B responds with another redirect to URL C.
  4. URL C, in turn, may redirect to a final destination, URL D.
The entire sequence (A -> B -> C -> D) constitutes a redirect chain. Redirect chains are common in web development and can impact page loading times and user experience. Developers often analyze and optimize redirect chains to ensure efficient and smooth navigation for users.

How to get the initial redirect location from a chain of multiple redirects?

✅ We can retrieve the header location using the get_headers() method. The header location is return as a string, but if there are multiple redirect chains, it will be returned as an array.

If you want the initial header location, you can obtain it from the 0th index. If you're interested in the final destination of the redirect, you can retrieve it from the last index.
<?php

function get_first_redirect_location($destination) {
    $headers        = get_headers($destination, 1);
    $first_location = (is_array($headers['Location'])) ? $headers['Location'][0] : $headers['Location'];
    return $first_location;
}

function get_final_redirect_location($destination) {
    $headers        = get_headers($destination, 1);
    if(is_array($headers['Location'])) {
        foreach($headers['Location'] as $key => $location) {
            if(count($headers['Location'])-1 == $key) {
                $final_location = $location;
            }
        }
    }
    else {
        $final_location = $headers['Location'];
    }
    return $final_location;
}

echo "First Redirect Location: ".get_first_redirect_location('http://www.buggerspot.com/')."</br>";
echo "Final Redirect Location: ".get_final_redirect_location('http://www.buggerspot.com/');

Thank You!