PHP waiting for correct response with cURL

我的未来我决定 提交于 2020-01-04 09:01:35

问题


I don't know how to make this. There is an XML Api server and I'm getting contents with cURL; it works fine. Now I have to call the creditCardPreprocessors state. It has 'in progress state' too and PHP should wait until the progess is finished. I tried already with sleep and other ways, but I can't make it. This is a simplified example variation of what I tried:

function process_state($xml){
  if($result = request($xml)){
  // It'll return NULL on bad state for example
    return $result;
  }
  sleep(3);
  process_state($xml);
}

I know, this can be an infite loop but I've tried to add counting to exit if it reaches five; it won't exit, the server will hang up and I'll have 500 errors for minutes and Apache goes unreachable for that vhost.

EDIT:

Another example

$i = 0;
$card_state = false;

// We're gona assume now the request() turns back NULL if card state is processing TRUE if it's done

while(!$card_state && $i < 10){
    $i++;
    if($result = request('XML STUFF')){
        $card_state = $result;
        break;
    }
    sleep(2);
}

回答1:


The recursive method you've defined could cause problems depending on the response timing you get back from the server. I think you'd want to use a while loop here. It keeps the requests serialized.

$returnable_responses = array('code1','code2','code3'); // the array of responses that you want the function to stop after receiving
$max_number_of_calls = 5; // or some number

$iterator = 0;
$result = NULL;
while(!in_array($result,$returnable_responses) && ($iterator < $max_number_of_calls)) {
    $result = request($xml);
    $iterator++; 
}


来源:https://stackoverflow.com/questions/14178859/php-waiting-for-correct-response-with-curl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!