dongtuan1980 2013-05-15 07:12
浏览 57

如何使PHP请求GET异步

I want to make PHP request GET asynchronous, but my version PHP is 5.2.13 and the version of curl is 7.16.4, that has many limits.

I tried:

curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);

But it does not work. As I know, that just works from PHP 5.2.3

So I read the other solution fsockopen:

function curl_request_async($url, $params, $type='POST')
  {
      if (count($params)>0){
          $post_params = array();

          foreach ($params as $key => &$val) {
            if (is_array($val)) $val = implode(',', $val);
            $post_params[] = $key.'='.urlencode($val);
          }
          $post_string = implode('&', $post_params);
      }

      $parts    =   parse_url($url);

      $fp = fsockopen($parts['host'],
          isset($parts['port'])?$parts['port']:80,
          $errno, $errstr, 30);

      // Data goes in the path for a GET request
      if(('GET' == $type)&& isset($post_string)) $parts['path'] .= '?'.$post_string;

      $out = "$type ".$parts['path']." HTTP/1.1
";
      $out.= "Host: ".$parts['host']."
";
      $out.= "Content-Type: application/x-www-form-urlencoded
";
      $out.= "Content-Length: ".strlen($post_string)."
";
      $out.= "Connection: Close

";
      // Data goes in the request body for a POST request
      if ('POST' == $type && isset($post_string)) $out.= $post_string;

      fwrite($fp, $out);
      fclose($fp);
  }

that works with POST but that does not work with GET. I want to make the request GET asynchronous

Anyone can help me ?

Thank you so much

  • 写回答

1条回答 默认 最新

  • dongmubi4375 2013-05-15 07:40
    关注

    Why would you want to make a web request respond asynchronously? HTTP requests are meant to be responded synchronously.

    I would suggest that if you would like to decouple a long running request/process in the backend from the front end so the response is more snappy, would be to use a background PHP worker, over rabbitMQ or beanstalkd, and have that run your long running process in the background. Your HTTP request would simply return a job ID, which you can use to make another call to check on the status of the long running job. Additionally, when the job is done, you can have it make a call back to notify the caller that the job is done, so additional trigger or programming flow could be continued.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100