PHP Class Curl Multi Example



<?php
$cm = new CurlMulti();
$cm->add("http://example.com/somelargefile1.zip",'./somelargefile1.zip');
$cm->add("http://example.com/somelargefile2.zip",'./somelargefile2.zip');
$cm->add("http://example.com/somelargefile3.zip",'./somelargefile3.zip');
$cm->add("http://example.com/somelargefile4.zip",'./somelargefile4.zip');
$cm->fetchAll();
?>
<?php
 
class CurlMulti
{
    private $curl_multi_handle = null;
    private $curl_handles = array();
 
    public function __construct()
    {
        $this->curl_multi_handle = curl_multi_init();
    }
 
    public function __destruct()
    {
        foreach($this->curl_handles as $dest=>$curl_handle)
        {
            curl_multi_remove_handle($this->curl_multi_handle, $curl_handle);
        }
        curl_multi_close($this->curl_multi_handle);
    }
 
    public function add($url,$dest,$options = array())
    {
        file_put_contents($dest,'');//write stub
 
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_HEADER, 0);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        foreach($options as $k=>$v)
        {
            //curl_setopt($ch1, $k, $v);
        }
        $this->curl_handles[ $dest ] = $ch1;
        curl_multi_add_handle($this->curl_multi_handle, $ch1);
    }
 
    public function fetchAll()
    {
        $mh = &$this->curl_multi_handle;
        $active = null;
        //execute the handles
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
 
        while ($active && $mrc == CURLM_OK) {
            if (curl_multi_select($mh) != -1) {
                do {
                    $mrc = curl_multi_exec($mh, $active);
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }
 
        foreach($this->curl_handles as $dest=>$curl_handle)
        {
            $content = curl_multi_getcontent($curl_handle);
            file_put_contents($dest,$content);
        }
    }
}
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)