file_get_contents如果失败,请使用其他服务器

What would be a good way to use backup server if needed in php function, using file_get_contents.

I could think of something like this, not sure if it would work as expected.

<?php

$data = file_get_contents("http:/server1.com"); // Lets say this is down (timeout or other error)
if(!$data){
    $data = file_get_contents("http://server1backup.com");
}
//do something with data


?>

Maybe somehow with try block ? Never used them before...

I also would like to set file_get_contents timeout shorter time, like 5 seconds, so it would not wait too long on 1 server if its down.

file_get_contents

doesn't throw an exception so try/catch block is not useful in this situation. Remember what is in the documentaion (http://php.net/manual/en/function.file-get-contents.php): on failure return value is FALSE, but sometimes on success you can get a falsy value (use === operator).

To change timeout use

ini_set('default_socket_timeout', 900);

More about ini parameter: http://php.net/manual/en/filesystem.configuration.php#ini.default-socket-timeout