2010-04-22 36 views
10

Aquí está mi código actual:¿Cómo puedo usar cURL para abrir varias URL simultáneamente con PHP?

$SQL = mysql_query("SELECT url FROM urls") or die(mysql_error()); //Query the urls table 
while($resultSet = mysql_fetch_array($SQL)){ //Put all the urls into one variable 

       // Now for some cURL to run it. 
      $ch = curl_init($resultSet['url']); //load the urls 
      curl_setopt($ch, CURLOPT_TIMEOUT, 2); //No need to wait for it to load. Execute it and go. 
      curl_exec($ch); //Execute 
      curl_close($ch); //Close it off 
     } //While loop 

soy relativamente nuevo para rizar. Por relativamente nuevo, me refiero a que esta es la primera vez que uso cURL. Actualmente carga uno por dos segundos, luego carga el siguiente durante 2 segundos, luego el siguiente. sin embargo, quiero que cargue TODOS al mismo tiempo. Estoy seguro de que es posible, no estoy seguro de cómo. Si alguien pudiera señalarme en la dirección correcta, lo agradecería.

+0

¿Necesita hacer algo con los resultados curl loads? –

+0

No. Nada en absoluto. – Rob

Respuesta

8

Configura cada identificador de CURL de la misma manera, luego agréguelos a un controlador curl_multi_. Las funciones a mirar son las funciones curl_multi_*documented here. En mi experiencia, sin embargo, hubo problemas al tratar de cargar demasiadas URL a la vez (aunque no puedo encontrar mis notas en este momento), así que la última vez que usé curl_mutli_, lo configuré para hacer lotes de 5 URL a la vez.

edición: Esta es una versión reducida del código que he usando curl_multi_:

edición: ligeramente reescrito y un montón de comentarios agregados, que se espera ayude.

// -- create all the individual cURL handles and set their options 
$curl_handles = array(); 
foreach ($urls as $url) { 
    $curl_handles[$url] = curl_init(); 
    curl_setopt($curl_handles[$url], CURLOPT_URL, $url); 
    // set other curl options here 
} 

// -- start going through the cURL handles and running them 
$curl_multi_handle = curl_multi_init(); 

$i = 0; // count where we are in the list so we can break up the runs into smaller blocks 
$block = array(); // to accumulate the curl_handles for each group we'll run simultaneously 

foreach ($curl_handles as $a_curl_handle) { 
    $i++; // increment the position-counter 

    // add the handle to the curl_multi_handle and to our tracking "block" 
    curl_multi_add_handle($curl_multi_handle, $a_curl_handle); 
    $block[] = $a_curl_handle; 

    // -- check to see if we've got a "full block" to run or if we're at the end of out list of handles 
    if (($i % BLOCK_SIZE == 0) or ($i == count($curl_handles))) { 
     // -- run the block 

     $running = NULL; 
     do { 
      // track the previous loop's number of handles still running so we can tell if it changes 
      $running_before = $running; 

      // run the block or check on the running block and get the number of sites still running in $running 
      curl_multi_exec($curl_multi_handle, $running); 

      // if the number of sites still running changed, print out a message with the number of sites that are still running. 
      if ($running != $running_before) { 
       echo("Waiting for $running sites to finish...\n"); 
      } 
     } while ($running > 0); 

     // -- once the number still running is 0, curl_multi_ is done, so check the results 
     foreach ($block as $handle) { 
      // HTTP response code 
      $code = curl_getinfo($handle, CURLINFO_HTTP_CODE); 

      // cURL error number 
      $curl_errno = curl_errno($handle); 

      // cURL error message 
      $curl_error = curl_error($handle); 

      // output if there was an error 
      if ($curl_error) { 
       echo(" *** cURL error: ($curl_errno) $curl_error\n"); 
      } 

      // remove the (used) handle from the curl_multi_handle 
      curl_multi_remove_handle($curl_multi_handle, $handle); 
     } 

     // reset the block to empty, since we've run its curl_handles 
     $block = array(); 
    } 
} 

// close the curl_multi_handle once we're done 
curl_multi_close($curl_multi_handle); 

Teniendo en cuenta que no es necesario nada de vuelta de las direcciones URL, es probable que no necesita una gran cantidad de lo que está allí, pero esta es la forma en que las solicitudes fragmentada en bloques de BLOCK_SIZE, esperaba a cada bloque para correr antes de continuar y detectar errores de cURL.

+0

Bueno, todo lo que voy a hacer es cargar cada url (y las urls que se cargarán son páginas en blanco, accediendo a las urls solo se inicia un script y se ejecuta durante un tiempo preestablecido) y no se guarda ni se emite cualquier información ¿Crees que causará algún problema en este caso? – Rob

+0

Supongo que no será un problema en ese caso, pero no estoy seguro: si no se ejecuta o si se producen errores al intentar cargarlos todos a la vez, puede poner un contador en su ciclo 'while' y cada vez' counter% batch_size == 0' dentro del ciclo, ejecute el lote y desactívelo. – Isaac

+0

Woah. Odio molestarte con esto, pero ¿podrías comentar algunas cosas en ese código para que yo pueda ver qué hace exactamente todo? – Rob

Cuestiones relacionadas