Skip to content

Instantly share code, notes, and snippets.

@juanpablocs
Created August 23, 2018 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanpablocs/3db5793f820f907d3d169b71939f3f59 to your computer and use it in GitHub Desktop.
Save juanpablocs/3db5793f820f907d3d169b71939f3f59 to your computer and use it in GitHub Desktop.
Fast multiple request with curl
<?php

class MultiRequest 
{
    /**
     * 
     * @param array $endpoints
     * <array>
     *   <identifier> identificador usado para devolver el response
     *     <url> URL a la que se le hace la petición
     *   <identifier>
     * <array>
     */
    public static function get(array $endpoints) 
    {
        $handlers = [];
        $mh = curl_multi_init();
        foreach ($endpoints as $identifier => $data) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $data['url']);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $handlers[$identifier] = $curl;
            curl_multi_add_handle($mh, $curl);
        }
        
        $running = null;
        do {
            curl_multi_exec($mh, $running);
        } while($running > 0);
        
        $result = [];
        foreach($handlers as $identifier => $curl) {
            $result[$identifier] = curl_multi_getcontent($curl);
            curl_multi_remove_handle($mh, $curl);
        }

        curl_multi_close($mh);
        return $result;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment