php发送curl请求并等待响应

时间:2013-11-06 16:28:08

标签: php curl

我向服务器发送curl请求,该服务器需要几秒钟来处理请求并吐出响应。我相信我的php脚本正在继续而不是等待,因此基于响应的foreach循环吐出0结果。在继续处理数据之前,我如何等待curl事务完成?

  $curl = curl_init();
  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  curl_setopt($curl, CURLOPT_USERPWD, "admin:password");
  curl_setopt($curl, CURLOPT_URL, "http://server/r/?dst_user__substr='user'");


  curl_setopt($curl, CURLOPT_VERBOSE, 1);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $ret = curl_exec($curl);
  $result = json_decode($ret,true);

 <<<<I need to wait until transaction is complete here>>>>

  foreach ($result['data'] as $key => $value)
  {
        //process data from $result
  }

2 个答案:

答案 0 :(得分:12)

curl阻塞,这意味着:

$result = json_decode($ret,true);

foreach ($result['data'] as $key => $value)
{
      //process data from $result
}

直到:

才会执行
$ret = curl_exec($curl);

已完成。您可以使用curl_error()检查错误和其他问题,并使用curl_getinfo()检查HTTP响应代码。

答案 1 :(得分:0)

这真的很奇怪! ,它不应该像你得到的那样发生。但无论如何尝试这样..

获取httpresponse代码,然后检查......

$curl = curl_init();
  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  curl_setopt($curl, CURLOPT_USERPWD, "admin:password");
  curl_setopt($curl, CURLOPT_URL, "http://server/r/?dst_user__substr='user'");


  curl_setopt($curl, CURLOPT_VERBOSE, 1);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $ret = curl_exec($curl);
  $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  if($httpcode==200)
  {
  $result = json_decode($ret,true);
  foreach ($result['data'] as $key => $value)
  {
        //process data from $result
  }
  }