<?php 

class Parallelget
{

    public $errors = array();
    public $info   = array();

    function __construct(){
        
    }
    
    
    function multi_curl($endpoint_urls, $timeout = 5)
    {

        // Create get requests for each URL
        $mh = curl_multi_init();
        foreach($endpoint_urls as $key => $endpoint)
        {
            $ch[$key] = curl_init($endpoint);
            curl_setopt($ch[$key], CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch[$key], CURLOPT_TIMEOUT, $timeout);
            curl_multi_add_handle($mh, $ch[$key]);
        }

        // Start performing the request
        $runningHandles = null;
        do {
            $execReturnValue = curl_multi_exec($mh, $runningHandles);
        } while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);

        // Loop and continue processing the request
        while ($runningHandles && $execReturnValue == CURLM_OK) {
            if (curl_multi_select($mh) != -1) {
             usleep(1);
            }

	        // Pull in any new data, or at least handle timeouts
	        do {
		        $execReturnValue = curl_multi_exec($mh, $runningHandles);
	        } while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
        }

        // Extract the content
        foreach($endpoint_urls as $key => $endpoint)
        {
            // Check for errors
            $this->errors[$key]['url']   = $endpoint;
            $this->errors[$key]['error'] = curl_error($ch[$key]);

            $info = curl_getinfo($ch[$key]);
            if($info["http_code"] == 200 && $this->errors[$key]['error'] == "") {
                $res[$key] = curl_multi_getcontent($ch[$key]);
            } else {
                $res[$key] = "";
            }
            
            $this->info[$key]['time_total']      = curl_getinfo($ch[$key], CURLINFO_TOTAL_TIME);
            $this->info[$key]['time_namelookup'] = curl_getinfo($ch[$key], CURLINFO_NAMELOOKUP_TIME);
            $this->info[$key]['time_connect']    = curl_getinfo($ch[$key], CURLINFO_CONNECT_TIME);
            $this->info[$key]['time_redir']      = curl_getinfo($ch[$key], CURLINFO_REDIRECT_TIME);

            // Remove and close the handle
            curl_multi_remove_handle($mh, $ch[$key]);
            curl_close($ch[$key]);
        }

        // Clean up the curl_multi handle
        curl_multi_close($mh);

        return $res;
    }

}

