如果超时,在php中重试curl请求? [英] Retry curl request if it times out in php?

查看:1534
本文介绍了如果超时,在php中重试curl请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以在php中失败后重试curl请求,如果超时,我希望它重试大约5次,但我不知道如何做到这一点。我应该使用 curl_errno($ ch)来检查是否是超时,然后运行一个全新的curl请求,还是有更简单的方法吗?

Is there a way to retry a curl request in php after it fails, I want it to retry about 5 times if it times out but I'm not sure how to do this. Should I use curl_errno($ch) to check if it's a time-out then run a whole new curl request, or is there an easier way to do it?

推荐答案

cURL有预定义的错误代码,您可以在这里找到它们: http://curl.haxx.se/libcurl/c/libcurl-errors.html
我们所关注的为28,表示CURLE_OPERATION_TIMEDOUT。它应该在curl_errno上返回数字,所以我们可以使用28比较来检查超时。

cURL has pre-defined error codes, you can find them here: http://curl.haxx.se/libcurl/c/libcurl-errors.html The one we're after is 28, for CURLE_OPERATION_TIMEDOUT. It should be returned numerically on curl_errno, so we can use the 28 comparison to check for timeouts.

我建议你循环,直到你没有得到28 ,您可以使用while来执行此操作,并添加并达到限制,例如

I'd suggest you loop through until you don't get the 28, you can do this with while and also add an and to reach the limit, like this

$limit  =   0;
while((curl_errno($ch) == 28 or $limit == 0) and $limit < 5){
    $limit++;
    // Run curl stuff
}

在循环中获取。所以是的,我想你需要再次运行curl命令。我还建议在重试之前放置一个睡眠,例如$ limit ++之后; line add

You should of course add your curl fetches in the loop too. So yes, I think you need to run the curl command again. I would also recommend placing a sleep before retrying to something like after the $limit++; line adding

if($limit > 0) sleep(1);

我假设这将在CLI上使用,所以睡眠不应该是一个问题。你只是不想敲一个HTTP服务器,你可能不知道它的防火墙规则和这样

I am assuming this will be used on the CLI so sleeps shouldn't be a problem. You just don't want to hammer a HTTP server, you may not know its firewall rules and such

这篇关于如果超时,在php中重试curl请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆