wintercounter
wintercounter

Reputation: 7468

PHP waiting for correct response with cURL

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);
}

Upvotes: 2

Views: 3498

Answers (1)

dethtron5000
dethtron5000

Reputation: 10841

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++; 
}

Upvotes: 2

Related Questions