php php发送curl请求并等待响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19817401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:05:53  来源:igfitidea点击:

php send curl request and wait for the response

phpcurl

提问by bart2puck

I am sending a curl request to a server that needs a few seconds to process the request and spit out a response. I believe my php script is continuing on and not waiting, therefore my foreach loop based on the response is spitting out 0 results. How can i wait for the curl transaction to complete before moving on and processing data?

我正在向服务器发送 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
  }

回答by Wayne Whitty

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 响应代码来检查错误和其他问题。

回答by Shankar Damodaran

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