Developer Snippet Diary

Multi-threading using curl php

<?php
// Initialize individual curl handles
$ch1 = curl_init("https://www.example.com");
$ch2 = curl_init("https://www.google.com");

// Set options (optional)
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

// Initialize the multi handle
$mh = curl_multi_init();

// Add the handles
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

// Execute all requests
$running = null; 
do { 
    curl_multi_exec($mh, $running); //runs as often as needed to move data forward, also it will update running to 2 because 2 process need to execute
    curl_multi_select($mh); // wait for activity def 1 second,  (reduces CPU usage) >ie Incoming data is ready to be read, Outgoing data can be sent, A socket state changes (connection established, closed, error, etc.)
} while ($running > 0);

// Get the content
$response1 = curl_multi_getcontent($ch1);
$response2 = curl_multi_getcontent($ch2);

// Close handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

curl_close($ch1);
curl_close($ch2);

// Output results
echo "Example.com:\n$response1\n";
echo "Google.com:\n$response2\n";

 

Posted by: R GONDAL
Email: rizikmw@gmail.com