Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a PHP while loop with function for condition

I'm using the following functions to get the final URL from a series of redirects...

https://stackoverflow.com/a/4102293/1183476

It works great 99.8% of the time. I can't really pinpoint the exception, but I believe it has something to do with the server on the other end generating a new random URL for each visit. Thus, this script gets stuck in an infinite loop.

To replicate the issue replace the get_redirect_url function with...

function get_redirect_url($url){
    return $url.'x';
}

The Question

How can I set a time or iteration limit?

I feel like I've tried everything. I tried putting a time based condition in the while loop that looks for the next URL, but its not working and I don't know why. Like this...

function get_all_redirects($url){
    $redirects = array();
    $start = time();
    while ($newurl = get_redirect_url($url) && time()-$start < 10 ){
        if (in_array($newurl, $redirects)){
            break;
        }
        $redirects[] = $newurl;
        $url = $newurl;
    }
    return $redirects;
}

I also tried counting iterations like this...

function get_all_redirects($url){
    $redirects = array();
    $i = 0;
    while ($newurl = get_redirect_url($url) && $i < 10 ){
        if (in_array($newurl, $redirects)){
            break;
        }
        $redirects[] = $newurl;
        $url = $newurl;
        $i++;
    }
    return $redirects;
}

The examples above are just 2 of many failed attempts. I'm ready for help. Thanks in advance.

like image 747
Kirkland Avatar asked Jun 28 '26 18:06

Kirkland


2 Answers

Just scanning (for a second) your code does not show any obvious problems but I would like to make some suggestions.

Whenever I see conditionals in control flow statements that use the result of an assignment it always smells fishy (ok, lets say its not my style):

while ($newurl = get_redirect_url($url) ...

I could bet that by yanking out that assignment/condition or whatever you want to call it, your code will become more readable and maintainable and by some happy chance fix the issue you are seeing.

like image 159
zaf Avatar answered Jul 01 '26 08:07

zaf


I am assuming, the loop you are talking of is a real loop, thus the iteration would not work, because of the break here breaks before incrementing if the url is in the array already.

if (in_array($newurl, $redirects)){
    break;
}

Why the timer doesn't work, I dont know. But fixing the incrementing by putting that $i++; at the top of the loop should at least improve your situation.

like image 26
MildlySerious Avatar answered Jul 01 '26 08:07

MildlySerious