Catching 502 error using file()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
benyboi
Forum Commoner
Posts: 80
Joined: Sat Feb 24, 2007 5:37 am

Catching 502 error using file()

Post 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 :)
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Catching 502 error using file()

Post 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();
}
 
benyboi
Forum Commoner
Posts: 80
Joined: Sat Feb 24, 2007 5:37 am

Re: Catching 502 error using file()

Post by benyboi »

Thanks :D

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

Thanks again
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Catching 502 error using file()

Post by Benjamin »

!==
Post Reply