2013-06-20 112 views
1

我使用curl_multi_exec()来并行请求多个网站。说,URL1,URL2,和URL3。只要其中一个网站返回结果,我就可以处理它,然后等待下一个响应。确定具体的卷曲多响应

现在我需要知道,基于请求的响应,这个结果来自哪个URL。我不能简单地检查响应中的URL,因为可能存在重定向。那么识别哪个URL(URL1URL2URL3)的响应来自哪个最好的方法是什么?可以从curl_multi_info_read()curl_getinfo()以某种方式使用该信息吗?是否有可以设置和请求的卷曲选项?

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

任何想法?

回答

0

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

$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); 
      ........ 
     } 
     } 
    } 
1

它可以将自定义的数据处理

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

,然后取这个数据

curl_getinfo($handle, \CURLINFO_PRIVATE);