Page 1 of 1

Catching 502 error using file()

Posted: Fri Mar 06, 2009 3:25 pm
by benyboi
Hello

I use file() in a script to read a remote webpage, but sometimes this remote site has problems and can cause a "502 bad gateway" error and so the rest of the script wont complete properly because the info wasnt loaded.

What would be the best way to deal with this error? I mean, retry loading the page if it fails? PHP does the whole on screen "

Code: Select all

 cant do this..." error stuff when the 502 error happens, so its not like the error slips through.

I know theres the try...catch method, but would this catch the 502 error?

Could i maybe do something like:
[syntax=php]$worked = 0;
while($worked == 0){
    try{
        file("...");
        if it worked set $worked = 1
    }catch(exception...){
        
    }
}
 [/syntax]

Any input is appreciated :)

Re: Catching 502 error using file()

Posted: Fri Mar 06, 2009 3:29 pm
by Benjamin
Per the manual file() returns false if it fails. If you need to catch the specific error code from the remote server I would recommend using curl. You could wrap the code in a try/catch block as well.

Code: Select all

 
try {
    if (false === ($data = file('http://foo.com/exec.php'))) {
        throw new Exception('file() failed to retrieve data from remote source');
    }
} catch (Exception $e) {
    echo $e->getMessage();
    exit();
}
 

Re: Catching 502 error using file()

Posted: Fri Mar 06, 2009 3:44 pm
by benyboi
Thanks :D

Can i just ask, is the opposite of === !==? or !===?

Thanks again

Re: Catching 502 error using file()

Posted: Fri Mar 06, 2009 3:45 pm
by Benjamin
!==