开发者

How can i add exception?

I have a php site www.test.com.

In the index page of this site ,i am updating another site's(www.pgh.com) database by the following php code.

$url = "https://pgh.com/test.php?userID=".$userName. "&password=" .$password ;
$response = file_get_contents($url); 

But,now the site www.pgh.co开发者_C百科m is down.So it also affecting my site 'www.test.com'.

So how can i add some exception or something else to this code,so that my site should work if other site is down


$response = file_get_contents($url);
if(!$response)
{
    //Return error
}

From the PHP manual Adding a timeout:

$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
        )
    )
);
file_get_contents("http://example.com/", 0, $ctx); 

file_get_contents returns false on fail.


You have two options:

  • Add a timeout to the file_get_contents call using stream_get_context() (The manual has good examples; Docs for the timeout parameter here). This is not perfect, as even a one second's timeout will cause a notable pause when loading the page.

  • More complex but better: Use a caching mechanism. Do the file_get_contents request in a separate script that gets called frequently (e.g. every 15 minutes) using a cron job (if you have access to one). Write the result to a local file, which your actual script will read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜