bobopu
V2EX  ›  PHP

使用file_get_contents远程调用一个纯文本总是超时怎么办?

  •  
  •   bobopu · Aug 26, 2013 · 7095 views
    This topic created in 4818 days ago, the information mentioned may be changed or developed.
    RT,使用file_get_contents('http://xxxx.com/xxxx.txt');刚开始还可以,过上一阵就总是超时调用不了了,这该怎么办?
    16 replies  •  1970-01-01 08:00:00 +08:00
    BOYPT
    BOYPT
    Aug 26, 2013
    1
    配置一个超时参数:

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


    外部资源属于不可控因素,程序里面要做好这类异常处理。
    bobopu
    bobopu
    OP
    Aug 26, 2013
    2
    @BOYPT 请问当大于设定的时间时是不显示,还是输出错误代码呢?
    anewg
    anewg
    Aug 26, 2013
    3
    @bobopu file_get_contents返回false
    lusin
    lusin
    Aug 26, 2013
    4
    用curl好像会好一些
    bobopu
    bobopu
    OP
    Aug 26, 2013❤️1
    5
    @BOYPT
    @anewg 提示
    Warning: file_get_contents(http://xxxx.com/xxxx.txt) [function.file-get-contents]: failed to open stream: Connection timed out in /home/xxx/xxx on line 8
    BOYPT
    BOYPT
    Aug 26, 2013
    6
    @bobopu 这要你自己决定啊,超时之后是自动重试、显示给用户、还是换一个地址,你都知道这一步了下一步自然自己决定了。
    hennywei
    hennywei
    Aug 26, 2013
    7
    建议用curl
    itaotao
    itaotao
    Aug 26, 2013
    8
    set_time_limit(0)
    anewg
    anewg
    Aug 26, 2013
    9
    @bobopu 你连接的页面要存在才返回false,你在写个test.php,里面sleep(10)。file_get_contents("http://localhost/test.php", 0, $ctx)返回的就是false
    Sokos
    Sokos
    Aug 26, 2013
    10
    尽量不用 file_get_contents。参考这文章 http://www.s135.com/file_get_contents
    hello570111
    hello570111
    Aug 26, 2013
    12
    file_get_contents默认没有超时时间,而且出错之后会终止整个程序而不是继续执行后面的语句,最多调试的时候用用,正式情况下最好用curl。
    bobopu
    bobopu
    OP
    Aug 26, 2013
    13
    @anewg 哦哦,我要调用的是纯文本文件,咋弄?
    bobopu
    bobopu
    OP
    Aug 26, 2013
    14
    @hennywei
    @hello570111
    @BOYPT 换做curl后又提示Fatal error: Call to undefined function curl() in /xxx/xxx.php on line 8 了。。。。
    hello570111
    hello570111
    Aug 26, 2013 via Android
    15
    @bobopu 因为php没有curl()这个函数,它不是这么用的(吐槽一下,难怪大家都喜欢用file_get_contents,太方便了),需要先curl_init()再curl_setopt()设置什么的。搜索一下“php curl使用”就知道了,可以自己再封装一下。
    bobopu
    bobopu
    OP
    Aug 26, 2013
    16
    @hello570111 好吧,我真是太菜了。。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2580 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 71ms · UTC 15:13 · PVG 23:13 · LAX 07:13 · JFK 10:13
    ♥ Do have faith in what you're doing.