motivation: - simplify code by using a common method for making single- or multi-curl requests
usage: - create a file, e.g. “curl.inc”, on your server and copy the code below w/ comment “multi curl util” into it - create another file, e.g. “curl_test.php”, on your server and copy the code below w/ comment “test” into it - browse to yourdomain.com/yourpath/curl_test.php - comment-out or -in the various examples in the test code to see some common use cases
notes: - only get and post are supported - if you see a way to improve the code, please leave a comment.
[sourcecode language=“php”] $v){ $pairs[] = “$k=$v”; } $param_str = implode(’&’, $pairs); $url .= ‘?’.$param_str; //set options $options = array( CURLOPT_URL => $url, CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true ); curl_setopt_array($ch, $options); return $ch; }
function create_post_handle($url, $params){ $ch = curl_init(); //format params foreach($params as $k => $v){ $pairs[] = “$k=$v”; } $params = implode(’&’, $pairs); //set options $options = array( CURLOPT_URL => $url, CURLOPT_POST=> true, CURLOPT_POSTFIELDS => $params, CURLOPT_RETURNTRANSFER => true, ); curl_setopt_array($ch, $options); return $ch; }
function curl($requests){ $mh = curl_multi_init(); //prep each request foreach($requests as $index => $request){ switch($request[‘method’]){ case ‘post’: $chs[$index] = create_post_handle($request[‘url’], $request[‘params’]); break; case ‘get’: $chs[$index] = create_get_handle($request[‘url’], $request[‘params’]); break; } curl_multi_add_handle($mh,$chs[$index]); } //credit: http://www.phpied.com/simultaneuos-http-requests-in-php-with-curl/ // execute the handles $running = null; do { curl_multi_exec($mh, $running); } while($running > 0); // get content and remove handles foreach($chs as $index => $ch) { $results[$index] = curl_multi_getcontent($ch); curl_multi_remove_handle($mh, $ch); } // all done curl_multi_close($mh); return $results; } [/sourcecode]
[sourcecode language=“php”]