phphttp-redirectget-headers

PHP get_headers recursively


I'm trying to implement a header response to follow recursevely headers redirects. I've implemented the following which works correctly for the first request, but if a location redirect is found in the header, the get_headers do not return any result for the redirected location. I would like to display the header for each header request.

This is what I have done.

function redirectURL($domain) {

$newLocation = '';  
$domain = str_replace("\r", "", $domain);

$headers=get_headers($domain);

echo "<ul class='list-group' >";

print "<li class='list-group-item'>".$domain. "</li>";
            foreach($headers as $k=>$v){
                print "<li class='list-group-item'>".$k . ": " . $v . "</li>";
                if(strstr($v, 'Location')){
                    $location = explode(":",$v);
                    $newLocation = $location[1].":".$location[2];
                }
            }
echo "</ul>";   

if($newLocation != $domainName && $newLocation != ''){
    redirectURL($newLocation);
}

unset($headers);

return true;
}

Any idea? I've a online implementation ... if need to see a working code. Thank you


Solution

  • Ok it was just bad coding. I've made it working. This is a working code

    function redirectURL($domainName) {
    
    $i=0;
    $newLocation = '';
    $isNew = false;
    $headers = array();
    $domainName = str_replace("\r", "", $domainName);
    
    $headers=get_headers($domainName,1);
    
    
    
    echo "<ul class='list-group' >";
    
    print "<li class='list-group-item'><strong>".$domainName. "</strong></li>";
                foreach($headers as $k => $v){
                    print "<li class='list-group-item'>".$k . ": " . $v . "</li>";
    
                        if($k ==  'Location'){
    
                            $newLocation = $v;
                            $isNew = true;
                            print "<li class='list-group-item'><strong>".$k . ": " . $v . "</strong></li>";
                        }
    
                }
    echo "</ul>";   
    
    unset($headers);
    //limit recurse to $i < 4 to avoid overload
    if($isNew){
        $i++;
        if($i<4) {redirectURL($newLocation);}
    
    }
    
    return true;
    }
    

    You can check the working script at https://www.neting.it/risorse-internet/controlla-redirect-server.html