确定特定的卷曲多重响应

时间:2013-06-20 12:47:21

标签: php curl curl-multi

我使用curl_multi_exec()并行请求多个网站。比方说,URL1URL2URL3。只要其中一个网站返回结果,我就可以处理它,然后等待下一个响应。

现在我需要根据请求的响应知道这个结果来自哪个URL。我不能简单地检查响应中的URL,因为可能存在重定向。那么,确定响应来自哪个网址(URL1URL2URL3)的最佳方法是什么?来自curl_multi_info_read()curl_getinfo()的信息能以某种方式用于此吗?我可以设置并请求cURL选项吗?

我还尝试在请求URL之前存储cURL处理程序并将它们与curl_multi_info_read($curlMultiHandle)['handle']进行比较,但由于这是一种资源,因此它并不具有可比性。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

可以附加自定义数据来处理

curl_setopt($handle, \CURLOPT_PRIVATE, json_encode(['id' => $query_id]));

然后获取此数据

curl_getinfo($handle, \CURLINFO_PRIVATE);

答案 1 :(得分:0)

假设您有多个需要加载数据的Image对象。您并行运行请求,不知道下载完成的顺序。因此,在接收数据时,必须以某种方式识别具体的Image对象。而不是使用URL(可能在重定向后更改)作为Image对象的关联数组中的键,我建议采用以下简单方法。

    $mh = curl_multi_init();
    $activeHandles = array();
    $loadingImages = array();

    function loadImage(Image $image) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $image->getUrl());
      curl_multi_add_handle($mh, $ch);
      ...
      $this->loadingImages[] = $image;
      $activeHandles[] = $ch;
    }

    function retrieveImages() {
      // Somewhere you run curl_multi_exec($mh, $running).
      // Here you get the results.
      while ($result = curl_multi_info_read($mh)) {
        // How to get the data is out of our scope.
        // We are interested in identifying the image object.
        $ch = $result['handle'];
        $idx = array_search($ch, $activeHandles);
        $image = $loadingImages[$idx];
        if ($success) {
          // Don't remember to free resources!
          unset($activeHandles[$idx]);
          unset($loadingImages[$idx]);
          curl_multi_remove_handle($mh, $ch);
          ........
        }
      }
    }
相关问题