简体   繁体   English

php发送curl请求并等待响应

[英]php send curl request and wait for the response

I am sending a curl request to a server that needs a few seconds to process the request and spit out a response. 我正在向服务器发送一个curl请求,该服务器需要几秒钟来处理请求并吐出响应。 I believe my php script is continuing on and not waiting, therefore my foreach loop based on the response is spitting out 0 results. 我相信我的php脚本正在继续而不是等待,因此基于响应的foreach循环吐出0结果。 How can i wait for the curl transaction to complete before moving on and processing data? 在继续处理数据之前,我如何等待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
  }

curl is blocking, which means that: curl是阻塞的,这意味着:

$result = json_decode($ret,true);

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

won't execute until: 将在以下情况下执行:

$ret = curl_exec($curl);

is complete. 完成了。 You can check for errors and other issues using curl_error() and by checking the HTTP response code with curl_getinfo(). 您可以使用curl_error()检查错误和其他问题,并使用curl_getinfo()检查HTTP响应代码。

This is really weird ! 这真是太奇怪了! , it shouldn't happen like what you are getting. ,它不应该像你得到的那样发生。 But anyways try like this.. 但无论如何尝试这样..

Get a httpresponse code and then check up... 获取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
  }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM